.
QGIS supports various capabilities for editing OGR, SpatiaLite, PostGIS, MSSQL Spatial and Oracle Spatial vector layers and tables.
Note
The procedure for editing GRASS layers is different - see section Digitalizando e editando as camadas vectoriais GRASS for details.
Tip
Edições Simultâneas
This version of QGIS does not track if somebody else is editing a feature at the same time as you are. The last person to save their edits wins.
Antes de podermos editar os vértices, necessitamos de configurar a tolerância e o raio de pesquisa para um valor que nos permita uma edição ideal das geometrias da camada vectorial.
Snapping tolerance is the distance QGIS uses to search for the closest vertex and/or segment you are trying to connect to when you set a new vertex or move an existing vertex. If you aren’t within the snapping tolerance, QGIS will leave the vertex where you release the mouse button, instead of snapping it to an existing vertex and/or segment. The snapping tolerance setting affects all tools that work with tolerance.
Note that this layer-based snapping overrides the global snapping option set in the Digitizing tab. So, if you need to edit one layer and snap its vertices to another layer, then enable snapping only on the snap to layer, then decrease the global snapping tolerance to a smaller value. Furthermore, snapping will never occur to a layer that is not checked in the snapping options dialog, regardless of the global snapping tolerance. So be sure to mark the checkbox for those layers that you need to snap to.
Figure Edit 1:
Search radius is the distance QGIS uses to search for the closest vertex you are trying to move when you click on the map. If you aren’t within the search radius, QGIS won’t find and select any vertex for editing, and it will pop up an annoying warning to that effect. Snap tolerance and search radius are set in map units or pixels, so you may find you need to experiment to get them set right. If you specify too big of a tolerance, QGIS may snap to the wrong vertex, especially if you are dealing with a large number of vertices in close proximity. Set search radius too small, and it won’t find anything to move.
The search radius for vertex edits in layer units can be defined in the
Digitizing tab under Settings ‣
Options. This is the same place where you define the general, project-
wide snapping tolerance.
Antes de editar uma camada, deve fazer uma ampliação à zona da área de interesse. Isto evita que espere enquanto os marcadores dos vértices são renderizados em toda a camada.
Além de usar os ícones mover mapa e
aproximar /
afastar na barra de ferramentas com o rato, a navegação pode também ser feita com a roda do rato, espaço e as teclas de direcção.
While digitizing, you can press the mouse wheel to pan inside of the main
window, and you can roll the mouse wheel to zoom in and out on the map.
For zooming, place the mouse cursor inside the map area and roll it forward
(away from you) to zoom in and backwards (towards you) to zoom out. The mouse
cursor position will be the center of the zoomed area of interest. You can
customize the behavior of the mouse wheel zoom using the Map tools
tab under the Settings ‣
Options menu.
Panning the map during digitizing is possible with the arrow keys. Place the mouse cursor inside the map area, and click on the right arrow key to pan east, left arrow key to pan west, up arrow key to pan north, and down arrow key to pan south.
You can also use the space bar to temporarily cause mouse movements to pan the map. The PgUp and PgDown keys on your keyboard will cause the map display to zoom in or out without interrupting your digitizing session.
Besides layer-based snapping options, you can also define topological
functionalities in the Snapping options... dialog in the
Settings (or File) menu. Here, you can
define Enable topological editing,
and/or for polygon layers, you can activate the column
Avoid Int., which avoids intersection of new polygons.
The option Enable topological editing is for editing
and maintaining common boundaries in polygon mosaics. QGIS ‘detects’ a
shared boundary in a polygon mosaic, so you only have to move the vertex
once, and QGIS will take care of updating the other boundary.
The second topological option in the Avoid Int.
column, called Avoid intersections of new polygons, avoids
overlaps in polygon mosaics. It is for quicker digitizing of adjacent
polygons. If you already have one polygon, it is possible with this option
to digitize the second one such that both intersect, and QGIS then cuts the
second polygon to the common boundary. The advantage is that you don’t
have to digitize all vertices of the common boundary.
Another option is to use Enable snapping on intersection.
It allows you to snap on an intersection of background layers, even if there’s no vertex on
the intersection.
By default, QGIS loads layers read-only. This is a safeguard to avoid accidentally editing a layer if there is a slip of the mouse. However, you can choose to edit any layer as long as the data provider supports it, and the underlying data source is writable (i.e., its files are not read-only).
In general, tools for editing vector layers are divided into a digitizing and an advanced digitizing toolbar, described in section Digitalização Avançada. You can select and unselect both under View ‣ Toolbars ‣. Using the basic digitizing tools, you can perform the following functions:
Edição da Tabela: Edição básica da camada vectorial pela barra de ferramentas
All editing sessions start by choosing the
Toggle editing option. This can be found in the context menu
after right clicking on the legend entry for a given layer.
Alternatively, you can use the Toggle Editing
Toggle editing button from the digitizing toolbar to start or stop the
editing mode. Once the layer is in edit mode, markers will appear at the
vertices, and additional tool buttons on the editing toolbar will become
available.
Tip
Guardar Regularmente
Lembre-se de Guardar Edições da Camada regularmente. Isto irá também verificar que a sua fonte de dados aceita todas as alterações.
Pode usar os ícones Adicionar Elemento,
Adicionar Elemento ou
Adicionar Elemento da barra de ferramentas para por o cursor QGIS no modo de digitalização.
Para cada elemento, primeiro digitaliza a geometria, e de seguida introduz os atributos. Para digitalizar a geometria, clique com o botão direito do rato na área do mapa para criar o primeiro ponto do seu novo elemento.
Para linhas e polígonos, mantenha o clique com o botão direito do rato para cada ponto adicional que pretende capturar. Quando acabar de adicionar os pontos, clique com o direito do rato em qualquer sítio da área do mapa para confirmar a finalização da introdução da geometria desse elemento.
The attribute window will appear, allowing you to enter the information for
the new feature. Figure_edit_2 shows setting attributes for a fictitious new
river in Alaska. In the Digitizing menu under the
Settings ‣ Options menu, you can also activate
Suppress attributes pop-up windows after each created feature and
Reuse last entered attribute values.
Figure Edit 2:
With the Move Feature(s) icon on the toolbar, you can
move existing features.
Tip
Tipos de Valores de Atributo
For editing, the attribute types are validated during entry. Because of this, it is not possible to enter a number into a text column in the dialog Enter Attribute Values or vice versa. If you need to do so, you should edit the attributes in a second step within the Attribute table dialog.
This feature allows the digitization of multiple layers. Choose
Save for Selected Layers to save all changes you
made in multiple layers. You also have the opportunity to
Rollback for Selected Layers, so that the
digitization may be withdrawn for all selected layers.
If you want to stop editing the selected layers,
Cancel for Selected Layer(s)
is an easy way.
The same functions are available for editing all layers of the project.
For shapefile-based layers as well as SpatialLite, PostgreSQL/PostGIS, MSSQL Spatial, and Oracle Spatial tables, the
Node Tool provides manipulation capabilities of
feature vertices similar to CAD programs. It is possible to simply select
multiple vertices at once and to move, add or delete them altogether.
The node tool also works with ‘on the fly’ projection turned on, and it supports
the topological editing feature. This tool is, unlike other tools in
QGIS, persistent, so when some operation is done, selection stays
active for this feature and tool. If the node tool is unable to find any
features, a warning will be displayed.
It is important to set the property Settings ‣
Options ‣ Digitizing ‣ Search Radius:
to a number greater than zero (i.e., 10). Otherwise, QGIS will
not be able to tell which vertex is being edited.
Comece por activar a Ferramenta de Nós e seleccione um elemento clicando em cima de um, As caixas vermelhos irão aparecer em cada vértice deste elemento.
Eliminar vértices: Depois de selecionar os vértices para eliminar, clique na tecla Delete. Note-se que não pode usar a Node Tool para eliminar um elemento completo; QGIS vais assegurar que mantém o número mínimo de vértices necessários para o tipo de elemento que está a trabalhar. Para eliminar um elemente completo, utilize a ferramenta
Delete Selected.
Mover vértices: Selecione todos os vértices que pretende mover. Clique num vértice selecionado ou na extreminade e arraste na direção que pretende mover. Todos os vértices selecionados serão movidos em conjunto. Se a ferramenta snapping está ativa, toda a seleção pode saltar para o vértice ou linha mais próximos.
Each change made with the node tool is stored as a separate entry in the Undo dialog. Remember that all operations support topological editing when this is turned on. On-the-fly projection is also supported, and the node tool provides tooltips to identify a vertex by hovering the pointer over it.
Selected features can be cut, copied and pasted between layers in the same
QGIS project, as long as destination layers are set to
Toggle editing beforehand.
Features can also be pasted to external applications as text. That is, the features are represented in CSV format, with the geometry data appearing in the OGC Well-Known Text (WKT) format.
However, in this version of QGIS, text features from outside QGIS cannot be pasted to a layer within QGIS. When would the copy and paste function come in handy? Well, it turns out that you can edit more than one layer at a time and copy/paste features between layers. Why would we want to do this? Say we need to do some work on a new layer but only need one or two lakes, not the 5,000 on our big_lakes layer. We can create a new layer and use copy/paste to plop the needed lakes into it.
As an example, we will copy some lakes to a new layer:
Carregue a camada que quer copiar a partir (camada de origem)
Carregue ou crie a camada que quer copiar para (camada de destino)
Começar a editar a camada de destino
Active a camada de origem clicando nela na legenda
Use a ferramenta Seleccione Elemento Único para seleccionar os elemento(s) na camada fonte
Active a camada de destino clicando na legenda
Parar a edição e guardar as alterações
What happens if the source and target layers have different schemas (field names and types are not the same)? QGIS populates what matches and ignores the rest. If you don’t care about the attributes being copied to the target layer, it doesn’t matter how you design the fields and data types. If you want to make sure everything - the feature and its attributes - gets copied, make sure the schemas match.
Tip
Congruência dos Elementos Colados
If your source and destination layers use the same projection, then the pasted features will have geometry identical to the source layer. However, if the destination layer is a different projection, then QGIS cannot guarantee the geometry is identical. This is simply because there are small rounding-off errors involved when converting between projections.
Se quisermos apagar o polígono todo, podemos faze-lo seleccionando o polígono usando a ferramenta Seleccionar Elemento Único. Pode seleccionar múltiplos elementos para apagar. Uma vez feita a selecção do conjunto, use a ferramenta
Apagar Seleccionados para apagar os elementos.
The Cut Features tool on the digitizing toolbar can
also be used to delete features. This effectively deletes the feature but
also places it on a “spatial clipboard”. So, we cut the feature to delete.
We could then use the
Paste Features tool to put it back,
giving us a one-level undo capability. Cut, copy, and paste work on the
currently selected features, meaning we can operate on more than one at a time.
When a layer is in editing mode, any changes remain in the memory of QGIS.
Therefore, they are not committed/saved immediately to the data source or disk.
If you want to save edits to the current layer but want to continue editing
without leaving the editing mode, you can click the
Save Layer Edits button. When you turn editing mode off with
Toggle editing (or quit QGIS for that matter),
you are also asked if you want to save your changes or discard them.
If the changes cannot be saved (e.g., disk full, or the attributes have values that are out of range), the QGIS in-memory state is preserved. This allows you to adjust your edits and try again.
Tip
Integridade dos dados
É sempre boa ideia fazer cópias de segurança da sua fonte de dados antes de começar a editar. Enquanto os autores do QGIS fizeram todo o esforço para preservar a integridade dos seus dados, nós não oferecemos garantia neste sentido.
Tabela de edição avançada: Barra de ferramentas de edição avançada de camadas vectoriais
The Undo and
Redo tools allows you
to undo or redo vector editing operations. There is also a dockable
widget, which shows all operations in the undo/redo history (see
Figure_edit_3). This widget is not displayed by default; it can be
displayed by right clicking on the toolbar and activating the Undo/Redo
checkbox. Undo/Redo is however active, even if the widget is not displayed.
Figure Edit 3:
When Undo is hit, the state of all features and attributes are reverted to the state before the reverted operation happened. Changes other than normal vector editing operations (for example, changes done by a plugin), may or may not be reverted, depending on how the changes were performed.
To use the undo/redo history widget, simply click to select an operation in the history list. All features will be reverted to the state they were in after the selected operation.
Use Rotate Feature(s) to rotate one or multiple
selected features in the map canvas. You first need to select the features
and then press the
Rotate Feature(s) icon. The
centroid of the feature(s) appears and will be the rotation anchor point. If you selected
multiple features, the rotation anchor point will be the common center of the features.
Press and drag the left mouse button in the desired direction to rotate the
selected features.
It’s also possible to create a user-defined rotation anchor point around which the selected feature will rotate.
Select the features to rotate and activate the Rotate Feature(s) tool.
Press and hold the Ctrl button and move the mouse pointer (without pressing the mouse button)
to the place where you want the rotation anchor to be moved. Release the Ctrl button
when the desired rotation anchor point is reached. Now, press and drag the left mouse button
in the desired direction to rotate the selected feature(s).
The Simplify Feature tool allows you to reduce the
number of vertices of a feature, as long as the geometry doesn’t change and
geometry type is not a multi geometry. First, select a feature. It will be
highlighted by a red rubber band and a slider will appear. Moving the slider,
the red rubber band will change its shape to show how the feature is being
simplified. Click [OK] to store the new, simplified geometry. If a feature
cannot be simplified (e.g. multi-polygons), a message will appear.
You can create ring polygons using the
Add Ring icon in the toolbar. This means that inside an existing area, it
is possible to digitize further polygons that will occur as a ‘hole’, so
only the area between the boundaries of the outer and inner polygons remains
as a ring polygon.
You can add part polygons to a selected
multipolygon. The new part polygon must be digitized outside
the selected multi-polygon.
You can use the Fill Ring function to add a ring to
a polygon and add a new feature to the layer at the same time. Thus you need not
first use the
Add Ring icon and then the
Add feature function anymore.
The Delete Ring tool allows you to delete ring polygons
inside an existing area. This tool only works with polygon layers. It doesn’t
change anything when it is used on the outer ring of the polygon. This tool
can be used on polygon and multi-polygon features. Before you select the
vertices of a ring, adjust the vertex edit tolerance.
The Delete Part tool allows you to delete parts from
multifeatures (e.g., to delete polygons from a multi-polygon feature). It won’t
delete the last part of the feature; this last part will stay untouched. This
tool works with all multi-part geometries: point, line and polygon. Before you
select the vertices of a part, adjust the vertex edit tolerance.
You can reshape line and polygon features using the
Reshape Features icon on the toolbar. It replaces the line or polygon
part from the first to the last intersection with the original line. With
polygons, this can sometimes lead to unintended results. It is mainly useful
to replace smaller parts of a polygon, not for major overhauls, and the reshape
line is not allowed to cross several polygon rings, as this would generate an
invalid polygon.
Por exemplo, pode editar o limite de um polígono com esta ferramenta. Primeiro, clique na área interna do polígos junto do ponto onde pretende adicionar o novo vértice. Depois, atravesse o limite e adicione os vértices no exterior do polígono. Para finalizar, clique com o botão direito na área interna do polígono. A ferramente vai adicionar um nó automaticamente no ponto onde a linha atravessa o limite. Também é possível remover parte da área do polígono, começa-se a nova linha no exterior do polígono, adicionam-se vértices no interior e termina-se a linha no exterior do polígono com um clique no botão direito.
Note
The reshape tool may alter the starting position of a polygon ring or a closed line. So, the point that is represented ‘twice’ will not be the same any more. This may not be a problem for most applications, but it is something to consider.
The Offset Curve tool creates parallel shifts of line layers.
The tool can be applied to the edited layer (the geometries are modified)
or also to background layers (in which case it creates copies of the lines / rings and adds them to the the edited layer).
It is thus ideally suited for the creation of distance line layers. The displacement is
shown at the bottom left of the taskbar.
To create a shift of a line layer, you must first go into editing mode and then
select the feature. You can make the Offset Curve tool active and drag
the cross to the desired distance. Your changes may then be saved with the
Save Layer Edits tool.
QGIS options dialog (Digitizing tab then Curve offset tools section) allows you to configure some parameters like Join style, Quadrant segments, Miter limit.
Pode dividir elementos usando o ícone Dividir Elementos da barra de ferramentas. Apenas desenhe uma linha ao longo do elemento que quer dividir.
In QGIS 2.0 it is now possible to split the parts of a multi part feature so that the
number of parts is increased. Just draw a line across the part you want to split using
the Split Parts icon.
The Merge Selected Features tool allows you to merge
features that have common boundaries. A new dialog will allow you to choose which
value to choose between each selected features or select a fonction (Minimum, Maximum,
Median, Sum, Skip Attribute) to use for each column.
The Merge Attributes of Selected Features tool
allows you to merge attributes of features with common boundaries and
attributes without merging their boundaries.
First, select several features at once. Then
press the
Merge Attributes of Selected Features button.
Now QGIS asks you which attributes are to be applied to all selected objects.
As a result, all selected objects have the same attribute entries.
Rotate Point Symbols allows you to change the rotation
of point symbols in the map canvas. You must first define a rotation column
from the attribute table of the point layer in the Advanced menu of the
Style menu of the Layer Properties. Also, you will need to
go into the ‘SVG marker’ and choose Data defined properties ....
Activate
Angle and choose ‘rotation’ as field.
Without these settings, the tool is inactive.
Figure Edit 4:
To change the rotation, select a point feature in the map canvas and rotate it, holding the left mouse button pressed. A red arrow with the rotation value will be visualized (see Figure_edit_4). When you release the left mouse button again, the value will be updated in the attribute table.
Note
Se segurar a tecla Ctrl premido, a rotação irá ser feita em passos de 15 graus.
QGIS allows you to create new shapefile layers, new SpatiaLite layers, and new GPX layers. Creation of a new GRASS layer is supported within the GRASS plugin. Please refer to section Criando uma nova camada vectorial GRASS for more information on creating GRASS vector layers.
To create a new shape layer for editing, choose New ‣
New Shapefile Layer... from the
Layer menu. The New Vector Layer dialog will be
displayed as shown in Figure_edit_5. Choose the type of layer (point, line or
polygon) and the CRS (coordinate reference system).
Note that QGIS does not yet support creation of 2.5D features (i.e., features with X,Y,Z coordinates).
Figure Edit 5:
To complete the creation of the new shapefile layer, add the desired attributes
by clicking on the [Add to attributes list] button and specifying a name and type for the
attribute. A first ‘id’ column is added as default but can be removed, if not
wanted. Only Type: real , Type: integer
, Type: string
and Type:date
attributes are supported. Additionally and according to the attribute type, you can also define
the width and precision of the new attribute column. Once you are happy with
the attributes, click [OK] and provide a name for the shapefile. QGIS will
automatically add a .shp extension to the name you specify. Once the
layer has been created, it will be added to the map, and you can edit it in the
same way as described in section Digitalizar uma camada existente above.
Para criar uma nova camada SpatialLite para edição, escolha Novo ‣ Nova Camada SpatiaLite... do menu Camada. O diálogo Nova Camada SpatiaLite irá aparecer como é mostrado na Figure_edit_6.
Figure Edit 6:
The first step is to select an existing SpatiaLite database or to create a new
SpatiaLite database. This can be done with the browse button to
the right of the database field. Then, add a name for the new layer, define
the layer type, and specify the coordinate reference system with [Specify CRS].
If desired, you can select
Create an autoincrementing primary key.
To define an attribute table for the new SpatiaLite layer, add the names of the attribute columns you want to create with the corresponding column type, and click on the [Add to attribute list] button. Once you are happy with the attributes, click [OK]. QGIS will automatically add the new layer to the legend, and you can edit it in the same way as described in section Digitalizar uma camada existente above.
Further management of SpatiaLite layers can be done with the DB Manager. See Módulo Gestor BD.
To create a new GPX file, you need to load the GPS plugin first. Plugins ‣
Plugin Manager... opens the Plugin Manager Dialog.
Activate the
GPS Tools checkbox.
When this plugin is loaded, choose New ‣
Create new GPX Layer... from the Layer menu.
In the Save new GPX file as dialog, you can choose where to save the
new GPX layer.
The attribute table displays features of a selected layer. Each row in the table represents one map feature, and each column contains a particular piece of information about the feature. Features in the table can be searched, selected, moved or even edited.
To open the attribute table for a vector layer, make the layer active by
clicking on it in the map legend area. Then, from the main
Layer menu, choose Open Attribute
Table. It is also possible to right click on the layer and choose
Open Attribute Table from the drop-down menu,
and to click on the
Open Attribute Table button
in the Attributes toolbar.
This will open a new window that displays the feature attributes for the layer (figure_attributes_1). The number of features and the number of selected features are shown in the attribute table title.
Figure Attributes 1:
Cada linha selecionada na tabela de atributos representa os atributos de um determinado elemento da camada. Se o conjunto de elementos selecionados na janela principal é alterado, a seleção também é atualizada na tabela de atributos. Da mesma forma, se um conjunto de linhas selecionadas na tabela de atributos é modificada, o conjunto de elementos selecionado na janela principal será atualizado.
As linhas podem ser selecionadas ao clicar no número da linha, do lado esquerdo desta. Podem ser marcadas Linhas múltiplas manter a tecla Ctrl primida. Pode ser feita uma seleção contínua se manter primida a tecla Shift e clicar na entrada de várias linha, do lado esquerdo. Todas as linhas entre a posição atual do cursor e a linha clicada serão selecionados. Ao mover a posição do cursor na tabela de atributos, ao clicar um célula na tabela, não tem influência na seleção de linhas. Modificar a seleção na tela principal não altera a posição do cursor na tabela de atributos.
A tabela pode ser ordenada por qualquer coluna, clicando no cabeçalho da coluna. Uma pequena seta indica a forma de ordenação (apontar para baixo significa valores descendentes do topo da linha, apontar para cima significa valores descendentes do topo da linha).
For a simple search by attributes on only one column, choose the Column filter ‣ from the menu in the bottom left corner. Select the field (column) on which the search should be performed from the drop-down menu, and hit the [Apply] button. Then, only the matching features are shown in the attribute table.
To make a selection, you have to use the Select features using an Expression
icon on top of the attribute table.
Select features using an Expression allows you
to define a subset of a table using a Function List like in the
Field Calculator (see Calculadora de Campos).
The query result can then be saved as a new vector layer.
For example, if you want to find regions that are boroughs from regions.shp
of the QGIS sample data, you have to open the Fields and Values menu
and choose the field that you want to query. Double-click the field ‘TYPE_2’ and also
[Load all unique values] . From the list, choose and double-click ‘Borough’.
In the Expression field, the following query appears:
"TYPE_2" = 'Borough'
Here you can also use the Function list ‣ Recent (Selection) to make a selection that you used before. The expression builder remembers the last 20 used expressions.
The matching rows will be selected, and the total number of matching rows will appear in the title bar of the attribute table, as well as in the status bar of the main window. For searches that display only selected features on the map, use the Query Builder described in section Ferramenta de Consulta.
To show selected records only, use Show Selected Features from the menu at the bottom left.
The other buttons at the top of the attribute table window provide the following functionality:
Below these buttons is the Field Calculator bar, which allows calculations
to be quickly applied attributes visible in the table. This bar uses the
same expressions as the Field Calculator
(see Calculadora de Campos).
Tip
Ignorar geometria WKT
If you want to use attribute data in external programs (such as Excel), use the
Copy selected rows to clipboard button.
You can copy the information without vector geometries if you deactivate
Settings ‣ Options ‣ Data sources menu
Copy geometry in WKT representation from attribute table.
The selected features can be saved as any OGR-supported vector format and
also transformed into another coordinate reference system (CRS). Just open
the right mouse menu of the layer and click on Save
as to define the name of the output file, its format and CRS (see section
Legenda do Mapa). To save the selection ensure that the
Save only selected features is selected.
It is also possible to specify OGR creation options within the dialog.
Features that are on the clipboard may be pasted into a new layer. To do this, first make a layer editable. Select some features, copy them to the clipboard, and then paste them into a new layer using Edit ‣ Paste Features as and choosing New vector layer or New memory layer.
This applies to features selected and copied within QGIS and also to features from another source defined using well-known text (WKT).
QGIS allows you also to load non-spatial tables. This currently includes tables
supported by OGR and delimited text, as well as the PostgreSQL, MSSQL and Oracle provider.
The tables can be used for field lookups or just generally browsed and edited using the table
view. When you load the table, you will see it in the legend field. It can be
opened with the Open Attribute Table tool and
is then editable like any other layer attribute table.
As an example, you can use columns of the non-spatial table to define attribute values, or a range of values that are allowed, to be added to a specific vector layer during digitizing. Have a closer look at the edit widget in section Menu Campos to find out more.
Relations are a technique often used in databases. The concept is, that features (rows) of different layers (tables) can belong to each other.
As an example you have a layer with all regions of alaska (polygon) which provides some attributes about its name and region type and a unique id (which acts as primary key).
Then you get another point layer or table with information about airports that are located in the regions and you also want to keep track of these. If you want to add them to the region layer, you need to create a one to many relation using foreign keys, because there are several airports in most regions.
Figure Relations 1:
In addition to the already existing attributes in the airports attribute table another field fk_region which acts as a foreign key (if you have a database, you will probably want to define a constraint on it).
This field fk_region will always contain an id of a region. It can be seen like a pointer to the region it belongs to. And you can design a custom edit form for the editing and QGIS takes care about the setup. It works with different providers (so you can also use it with shape and csv files) and all you have to do is to tell QGIS the relations between your tables.
QGIS makes no difference between a table and a vector layer. Basically, a vector layer is a table with a geometry. So can add your table as a vector layer. To demostrate you can load the ‘region’ shapefile (with geometries) and the ‘airport’ csv table (without geometries) and a foreign key (fk_region) to the layer region. This means, that each airport belongs to exactly one region while each region can have any number of airports (a typical one to many relation).
The first thing we are going to do is to let QGIS know about the relations between the layer. This is done in Settings ‣ Project Properties. Open the Relations menu and click on Add.
Figure Relations 2:
Now that QGIS knows about the relation, it will be used to improve the forms it generates. As we did not change the default form method (autogenerated) it will just add a new widget in our form. So let’s select the layer region in the legend and use the identify tool. Depending on your settings, the form might open directly or you will have to choose to open it in the identification dialog under actions.
Figure Relations 3:
As you can see, the airports assigned to this particular region are all shown in a table. And there are also some buttons available. Let’s review them shortly
If you work on the airport table, a new widget type is available which lets you embed the feature form of the referenced region on the feature form of the airports. It can be used when you open the layer properties of the airports table, switch to the Fields menu and change the widget type of the foreign key field ‘fk_region’ to Relation Reference.
If you look at the feature dialog now, you will see, that the form of the region is embedded inside the airports form and will even have a combobox, which allows you to assign the current airport to another region.
Figure Relations 4: