Outdated version of the documentation. Find the latest one here.

Lavorare col la tabella degli attributi

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 openTable Open Attribute Table. It is also possible to right click on the layer and choose openTable Open Attribute Table from the drop-down menu, and to click on the openTable 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:

../../../_images/vectorAttributeTable.png

Attribute Table for regions layer

The buttons at the top of the attribute table window provide the following functionality:

  • toggleEditing Toggle editing mode to enable editing functionalities (also with Ctrl+e)
  • saveEdits Save Edits (also with Ctrl+s)
  • draw Reload the table
  • newTableRow Add feature
  • deleteSelected Delete selected features (also with Ctrl+d)
  • expressionSelect Select features using an Expression
  • selectAll Select all (also with Ctrl+a)
  • invertSelection Invert selection (also with Ctrl+r)
  • unselectAttributes Unselect all (also with Ctrl+u)
  • selectedToTop Move selected to top (also with Ctrl+t)
  • panToSelected Pan map to the selected rows (also with Ctrl+p)
  • zoomToSelected Zoom map to the selected rows (also with Ctrl+j)
  • copySelected Copy selected rows to clipboard (also with Ctrl+c)
  • editPaste Paste from clipboard to a new row (also with Ctrl+v)
  • deleteAttribute Delete Column for PostGIS layers and for OGR layers with GDAL version >= 1.9 (also with Ctrl+l)
  • newAttribute New Column for PostGIS layers and for OGR layers with GDAL version >= 1.6 (also with Ctrl+w)
  • calculateField Open field calculator (also with Ctrl+i)

Below these buttons is the Field Calculator bar (enabled only in editing mode), which allows calculations to be quickly applied to either all or selected features attributes in the table. This bar uses the same expressions as the calculateField Field Calculator (see Field Calculator).

Suggerimento

Skip WKT geometry

If you want to use attribute data in external programs (such as Excel), use the copySelected Copy selected rows to clipboard button. You can copy the information without vector geometries if you deactivate Settings ‣ Options ‣ Data sources menu checkbox Copy geometry in WKT representation from attribute table.

Selecting features in an attribute table

Each selected row in the attribute table displays the attributes of a selected feature in the layer. If the set of features selected in the main window is changed, the selection is also updated in the attribute table. Likewise, if the set of rows selected in the attribute table is changed, the set of features selected in the main window will be updated.

Rows can be selected by clicking on the row number on the left side of the row. Multiple rows can be marked by holding the Ctrl key. A continuous selection can be made by holding the Shift key and clicking on several row headers on the left side of the rows. All rows between the current cursor position and the clicked row are selected. Moving the cursor position in the attribute table, by clicking a cell in the table, does not change the row selection. Changing the selection in the main canvas does not move the cursor position in the attribute table.

The table can be sorted by any column, by clicking on the column header. A small arrow indicates the sort order (downward pointing means descending values from the top row down, upward pointing means ascending values from the top row down).

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 expressionSelect Select features using an Expression icon on top of the attribute table. expressionSelect Select features using an Expression allows you to define a subset of a table using a Function List like in the calculateField Field Calculator (see Field Calculator). 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 Costruttore di interrogazioni.

To show selected records only, use Show Selected Features from the menu at the bottom left. See next section for more information on filter feature.

The field calculator bar allows you to make calculations on the selected rows only. For example, you can alter the number of the ID field of the layer regions.shp with the expression

ID+5

as shown in figure_attributes_1 .

Filter features

At the bottom of the attribute table, you have a dropdown list of different filter:

  • Show All Features;
  • Show Selected Features;
  • Show Features visible on map;
  • Show Edited and New Features;
  • Field Filter;
  • Advanced filter (Expression);

The first four are self explanatory, the two last are expression filters. Field Filter allows user to choose a column name in the list and add a simple form to the right of the drop-down list to filter with a like expression parameter. This filter will create an expression filter as an Advanced filter. The last kind of filter will open an expression window, see Expressions for more information.

Tab/form mode

By default the attribute window displays a table layout. In some case one should prefer to use a form layout to help edit some features more easily.

You can switch to form layout by clicking in the bottom right, on openForm and switch back to table layout with openTable.

Zoom to feature

To zoom into a feature, without having to select it, right-click on the feature you want to zoom in, within the attribute table, and select Zoom to feature.

Save selected features as new layer

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 Layers Panel). To save the selection ensure that the checkbox Save only selected features is selected. It is also possible to specify OGR creation options within the dialog.

Paste into new layer

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).

Editing attribute values

The calculateField Field Calculator button in the attribute table allows you to perform calculations on the basis of existing attribute values or defined functions, for instance, to calculate length or area of geometry features. The results can be written to a new attribute field, a virtual field, or they can be used to update values in an existing field.

A virtual field is a field based on an expression calculated on the fly, meaning that its value is automatically updated as soon as the underlying parameter changes. The expression is set once; you no longer need to recalculate the field each time underlying values change. For example, you may want to use a virtual field if you need area to be evaluated as you digitize features or to automatically calculate a duration between dates that may change (e.g., using now() function).

Nota

Use of Virtual Fields

  • Virtual fields are not permanent in the layer attributes, meaning that they’re only saved and available in the project file they’ve been created.
  • A field can be set virtual only at its creation and the expression used can’t be changed later: you’ll need to delete and recreate that field.

The field calculator is available on any layer that supports edit. When you click on the field calculator icon the dialog opens (see figure_attributes_2). If the layer is not in edit mode, a warning is displayed and using the field calculator will cause the layer to be put in edit mode before the calculation is made.

The quick field calculation bar on top of the attribute table is only visible if the layer is in edit mode.

In quick field calculation bar, you first select the existing field name then open the expression dialog to create your expression or write it directly in the field then click on [Update All], [Update Selected] or [Update Filtered] button according to your need.

Field Calculator

Based on the Expression Builder dialog, the field calculator dialog offers a complete interface to define an expression and apply it to an existing or a newly created field. To use the field calculator dialog, you first must select whether you want to only update selected features, create a new attribute field where the results of the calculation will be added or update an existing field.

Figure Attributes 2:

../../../_images/fieldcalculator.png

Field Calculator

If you choose to add a new field, you need to enter a field name, a field type (integer, real or string), the total field width, and the field precision (see figure_attributes_2). For example, if you choose a field width of 10 and a field precision of 3, it means you have 6 digits before the dot, then the dot and another 3 digits for the precision.

A short example illustrates how field calculator works when using the Expression tab. We want to calculate the length in km of the railroads layer from the QGIS sample dataset:

  1. Load the shapefile railroads.shp in QGIS and press openTable Open Attribute Table.
  2. Click on toggleEditing Toggle editing mode and open the calculateField Field Calculator dialog.
  3. Select the checkbox Create a new field checkbox to save the calculations into a new field.
  4. Add length as Output field name and real as Output field type, and define Output field width to be 10 and Precision, 3.
  5. Now double click on function $length in the Geometry group to add it into the Field calculator expression box.
  6. Complete the expression by typing / 1000 in the Field calculator expression box and click [Ok].
  7. You can now find a new field length in the attribute table.

Working with non spatial attribute tables

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 openTable 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 Campi to find out more.

Formattazione condizionale di celle

Puoi abilitare il pannello conditional formatting cliccando su rendererAttributeTable nella parte superiore destra della finestra della tabella degli attributi (non disponibile nella vista modulo).

Il nuovo pannello ti permette di aggiungere nuove regole per la formattazione condizionale dei campi o compilare righe dall’espressioni di campi. Aggiungendo una nuova regola apri un modulo per definire:

  • il nome della regola,

  • una condizione dalla finestra calcolatore,

  • una formattazione preimpostata

  • alcuni altri parametri per migliorare, cambiare o impostare la formattazione:

    • sfondo e colori del testo,

    • uso di icone,

    • grassetto, corsivo sottolineato o barrato,

    • colori testo,

    • carattere.

Figure Attributes 3:

../../../_images/attribute_table_conditional_formating.png

Formattazione condizionale di una tabella degli attributi

Creare relazioni uno a molti

Le relazioni sono una tecnica usata spesso nei database. Il concetto è che geometrie (righe) di diversi layer (tabelle) possono relazionarsi a vicenda.

Come esempio hai un livello con tutte le regioni dell’Alaska (poligono) con alcuni attributi sul suo nome e il tipo regione e un ID univoco (che funge da chiave primaria).

Chiavi esterne

Avrai un altro layer di punti o tabella con informazioni sugli aeroporti che si trovano nelle varie regioni. Se vuoi aggiungere la regione, devi creare una relazione uno a molti utilizzando chiavi esterne, perché ci sono diversi aeroporti nella maggior parte delle regioni.

Figure Relations 1:

../../../_images/relations1.png

Regione dell’Alaska con areoporti

In aggiunta agli attributi già esistenti nella tabella degli attributi di airports un’altro campo fk_region campo agisce come chiave esterna (se disponi di un database, probabilmente definirai un vincolo su di esso).

Questo campo fk_region conterrà sempre l’id di una regione. Esso può essere visto come un puntatore alla regione di appartenenza.Puoi progettare un modulo di modifica personalizzato per l’editing e QGIS lo configurerà. Funziona con diversi file sorgente (in modo da poter utilizzare anche shapefile e csv) e tutto quello che devi fare è dire QGIS le relazioni tra le tabelle.

Layer

QGIS fa differenza tra una tabella e un vettore. Fondamentalmente, un vettore è una tabella con una geometria. Così puoi aggiungere la tua tabella come un vettore. Puoi caricare la shapefile ‘region’ (con geometrie) e la tabella csv ‘airport’ (senza le geometrie) e una chiave esterna (fk_region) per il layer region. Ciò significa che ogni aeroporto appartiene ad una sola regione mentre ogni regione può avere più aeroporti (una tipica relazione uno a molti).

Definition (Relation Manager)

La prima cosa da fare è vedere come sono le realzoni tra layer in QGIS. Puoi farlo in Progetto ‣ Proprietà progetto. Apri il menu Relazioni e clicca su Aggiungi.

  • Nome sarà usato come titolo. Dovrebbe essere una stringa che descrive le finalità della relazione. In questo caso la chiamerai “Airports”.

  • Layer figlio è quello con il campo chiave esterna. Nel nostro caso questo è il layer airpots

  • Campo di riferimento dirà quale campo indicherà l’altro layer e in questo caso è fk_region

  • Layer padre è quello a cui punta la chiave primaria e in questo caso il layer regions

  • Campo a cui si fa riferimento è la chiave primaria che è ID del layer di riferimento padre

  • id verrà utilizzata per scopi interni e deve essere unica. Potrebbe essere necessaria per costruire i moduli personalizzati una volta che questo è supportato. Se la lasci vuota, ne verrà generata una automaticamente, ma è puoi assegnarne unaper semplificarne la gestione.

Figure Relations 2:

../../../_images/relations2.png

Relation Manager

Forms

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:

../../../_images/relations3.png

Identification dialog regions with relation to airports

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

  • The toggleEditing button is for toggling the edit mode. Be aware that it toggles the edit mode of the airport layer, although we are in the feature form of a feature from the region layer. But the table is representing features of the airport layer.
  • The signPlus button will add a new feature to the airport layer. And it will assign the new airport to the current region by default.
  • The remove button will delete the selected airport permanently.
  • The link symbol will open a new dialog where you can select any existing airport which will then be assigned to the current region. This may be handy if you created the airport on the wrong region by accident.
  • The unlink symbol will unlink the selected airport from the current region, leaving them unassigned (the foreign key is set to NULL) effectively.
  • The two buttons to the right switch between table view and form view where the later let’s you view all the airports in their respective form.

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:

../../../_images/relations4.png

Identification dialog airport with relation to regions