.
The Layer Properties dialog for a vector layer provides information about the layer, symbology settings and labeling options. If your vector layer has been loaded from a PostgreSQL/PostGIS datastore, you can also alter the underlying SQL for the layer by invoking the Query Builder dialog on the General tab. To access the Layer Properties dialog, double-click on a layer in the legend or right-click on the layer and select Properties from the pop-up menu.
Figure Vector Properties 1:
The Style menu provides you with a comprehensive tool for rendering and symbolizing your vector data. You can use Layer rendering ‣ tools that are common to all vector data, as well as special symbolizing tools that were designed for the different kinds of vector data.
The renderer is responsible for drawing a feature together with the correct symbol. There are four types of renderers: single symbol, categorized, graduated and rule-based. There is no continuous color renderer, because it is in fact only a special case of the graduated renderer. The categorized and graduated renderers can be created by specifying a symbol and a color ramp - they will set the colors for symbols appropriately. For point layers, there is a point displacement renderer available. For each data type (points, lines and polygons), vector symbol layer types are available. Depending on the chosen renderer, the Style menu provides different additional sections. On the bottom right of the symbology dialog, there is a [Symbol] button, which gives access to the Style Manager (see Presentation). The Style Manager allows you to edit and remove existing symbols and add new ones.
After having made any needed changes, the symbol can be added to the list of current style symbols (using [Symbol] Save in symbol library), and then it can easily be used in the future. Furthermore, you can use the [Save Style] button to save the symbol as a QGIS layer style file (.qml) or SLD file (.sld). SLDs can be exported from any type of renderer – single symbol, categorized, graduated or rule-based – but when importing an SLD, either a single symbol or rule-based renderer is created. That means that categorized or graduated styles are converted to rule-based. If you want to preserve those renderers, you have to stick to the QML format. On the other hand, it can be very handy sometimes to have this easy way of converting styles to rule-based.
Se cambi il tipo di visualizzatore mentre imposti lo stile di un vettore, le impostazioni effettuate per il simbolo saranno mantenute. Questo funziona solo per un cambiamento. Se si ripete la modifica del tipo di visualizzatore le impostazioni per il simbolo saranno perse.
If the datasource of the layer is a database (PostGIS or Spatialite for example), you can save your layer style inside a table of the database. Just click on Save Style comboxbox and choose Save in database item then fill in the dialog to define a style name, add a description, an ui file and if the style is a default style. When loading a layer from the database, if a style already exists for this layer, QGIS will load the layer and its style. You can add several style in the database. Only one will be the default style anyway.
Figure Vector Properties 2:
Suggerimento
Selezionare e cambiare simboli multipli
La Simbologia ti permette di scegliere simboli multipli e di cliccare con il tasto destro per cambiare il coloro, la trasparenza, la dimensione e lo spessore di quello che hai selezionato.
Single Symbol Renderer
The Single Symbol Renderer is used to render all features of the layer using a single user-defined symbol. The properties, which can be adjusted in the Style menu, depend partially on the type of layer, but all types share the following dialog structure. In the top-left part of the menu, there is a preview of the current symbol to be rendered. On the right part of the menu, there is a list of symbols already defined for the current style, prepared to be used by selecting them from the list. The current symbol can be modified using the menu on the right side.
If you click on the first level in the Symbol layers dialog on the left side, it’s possible to define basic parameters like Size, Transparency, color and Rotation. Here, the layers are joined together.
Figure Symbology 3:
In any spinbox in this dialog you can enter expressions. E.g. you can calculate simple math like multiplying the existing size of a point by 3 without resorting to a calculator.
Figure Symbology 4:
If you click on the second level in the Symbol layers dialog a ‘Data-defined override’ for nearly all settings is possible. When using a data-defined color one may want to link the color to a field ‘budged’. Here a comment functionality is inserted.
/* This expression will return a color code depending on the field value.
* Negative value: red
* 0 value: yellow
* Positive value: green
*/
CASE
WHEN value < 0 THEN '#DC143C' -- Negative value: red
WHEN value = 0 THEN '#CCCC00' -- Value 0: yellow
ELSE '#228B22' -- Positive value: green
END
Figure Symbology 5:
Categorized Renderer
The Categorized Renderer is used to render all features from a layer, using a single user-defined symbol whose color reflects the value of a selected feature’s attribute. The Style menu allows you to select:
Then click on Classify button to create classes from the distinct value of the attribute column. Each classes can be disabled unchecking the checkbox at the left of the class name.
You can change symbol, value and/or label of the class, just double click on the item you want to change.
Il tasto destro mostra un menù contestuale con Copia/Incolla, Cambia colore, Cambia trasparenza, Cambia unità, Cambia dimensione del simbolo**.
The [Advanced] button in the lower-right corner of the dialog allows you to set the fields containing rotation and size scale information. For convenience, the center of the menu lists the values of all currently selected attributes together, including the symbols that will be rendered.
The example in figure_symbology_6 shows the category rendering dialog used for the rivers layer of the QGIS sample dataset.
Figure Symbology 6:
Graduated Renderer
The Graduated Renderer is used to render all the features from a layer, using a single user-defined symbol whose color reflects the assignment of a selected feature’s attribute to a class.
Figure Symbology 7:
Like the Categorized Renderer, the Graduated Renderer allows you to define rotation and size scale from specified columns.
Also, analogous to the Categorized Renderer, the Style tab allows you to select:
Additionally, you can specify the number of classes and also the mode for classifying features within the classes (using the Mode list). The available modes are:
Intervallo uguale: ogni classe ha la stessa dimensione ( per esempio valori da 0 a 16 e quattro classi, ogni classe ha dimensione 4)
Quantile: ogni classe avrà lo stesso numero di elementi (l’idea di un diagramma a scatola e baffi)
Natural Breaks (Jenks): la varianza all’interno di ogni classe è minimo, mentre quella tra le classi è massima;
Deviazione standard: le classi sono costruite in funzione della deviazione standard dei valori;
Nella parte centrale della finestra Stile, puoi vedere tutte i valori e le classi di suddivisione insieme ai loro intervalli, etichette e simboli.
Click on Classify button to create classes using the choosen mode. Each classes can be disabled unchecking the checkbox at the left of the class name.
You can change symbol, value and/or label of the clic, just double clicking on the item you want to change.
Il tasto destro mostra un menù contestuale con Copia/Incolla, Cambia colore, Cambia trasparenza, Cambia unità, Cambia dimensione del simbolo**.
The example in figure_symbology_7 shows the graduated rendering dialog for the rivers layer of the QGIS sample dataset.
Suggerimento
Mappe tematiche usando un’espressione
Categorized and graduated thematic maps can now be created using the result of an expression. In the properties dialog for vector layers, the attribute chooser has been augmented with a Set column expression function. So now you no longer need to write the classification attribute to a new column in your attribute table if you want the classification attribute to be a composite of multiple fields, or a formula of some sort.
Rule-based rendering
The Rule-based Renderer is used to render all the features from a layer, using rule based symbols whose color reflects the assignment of a selected feature’s attribute to a class. The rules are based on SQL statements. The dialog allows rule grouping by filter or scale, and you can decide if you want to enable symbol levels or use only the first-matched rule.
The example in figure_symbology_8 shows the rule-based rendering dialog for the rivers layer of the QGIS sample dataset.
To create a rule, activate an existing row by double-clicking on it, or click on ‘+’ and click on the new rule. In the Rule properties dialog, you can define a label for the rule. Press the button to open the expression string builder. In the Function List, click on Fields and Values to view all attributes of the attribute table to be searched. To add an attribute to the field calculator Expression field, double click its name in the Fields and Values list. Generally, you can use the various fields, values and functions to construct the calculation expression, or you can just type it into the box (see Expressions). You can create a new rule by copying and pasting an existing rule with the right mouse button. You can also use the ‘ELSE’ rule that will be run if none of the other rules on that level match. Since QGIS 2.8 the rules appear in a tree hierarchy in the map legend. Just double-klick the rules in the map legend and the Style menu of the layer properties appears showing the rule that is the background for the symbol in the tree.
Figure Symbology 8:
Point displacement
The Point Displacement Renderer works to visualize all features of a point layer, even if they have the same location. To do this, the symbols of the points are placed on a displacement circle around a center symbol.
Figure Symbology 9:
Suggerimento
Esporta simbologia vettore
You have the option to export vector symbology from QGIS into Google *.kml, *.dxf and MapInfo *.tab files. Just open the right mouse menu of the layer and click on Save selection as ‣ to specify the name of the output file and its format. In the dialog, use the Symbology export menu to save the symbology either as Feature symbology ‣ or as Symbol layer symbology ‣. If you have used symbol layers, it is recommended to use the second setting.
Inverted Polygon
Inverted polygon renderer allows user to define a symbol to fill in outside of the layer’s polygons. As before you can select subrenderers. These subrenderers are the same as for the main renderers.
Figure Symbology 10:
Suggerimento
Switch quickly between styles
Once you created one of the above mentioned styles you can right-klick on the layer and choose Styles ‣ Add to save your style. Now you can easily switch between styles you created using the Styles ‣ menu again.
Heatmap
With the Heatmap renderer you can create live dynamic heatmaps for (multi)point layers. You can specify the heatmap radius in pixels, mm or map units, choose a color ramp for the heatmap style and use a slider for selecting a tradeoff between render speed and quality. When adding or removing a feature the heatmap renderer updates the heatmap style automatically.
Regardless the type of style to be used, the select color dialog will show when you click to choose a color - either border or fill color. This dialog has four different tabs which allow you to select colors by color ramp, color wheel, color swatches or color picker.
Whatever method you use, the selected color is always described through color sliders for HSV (Hue, Saturation, Value) and RGB (Red, Green, Blue) values. There is also an opacity slider to set transparency level. On the lower left part of the dialog you can see a comparison between the current and the new color you are presently selecting and on the lower right part you have the option to add the color you just tweaked into a color slot button.
Figure color picker 1:
With color ramp or with color wheel, you can browse to all possible color combinations. There are other possibilities though. By using color swatches you can choose from a preselected list. This selected list is populated with one of three methods: Recent colors, Standard colors or Project colors
Figure color picker 2:
Another option is to use the color picker which allows you to sample a color from under your mouse pointer at any part of QGIS or even from another application by pressing the space bar. Please note that the color picker is OS dependent and is currently not supported by OSX.
Suggerimento
quick color picker + copy/paste colors
You can quickly choose from Recent colors, from Standard colors or simply copy or paste a color by clicking the drop-down arrow that follows a current color box.
Figure color picker 3:
Trasparenza del layer : con questo strumento puoi decidere il grado di visibilità del vettore. Usa questo cursore per adattare la trasparenza del vettore. Puoi anche impostare un valore preciso di trasparenza nella casella presente a destra del cursore.
The Labels core application provides smart labeling for vector point, line and polygon layers, and it only requires a few parameters. This new application also supports on-the-fly transformed layers. The core functions of the application have been redesigned. In QGIS, there are a number of other features that improve the labeling. The following menus have been created for labeling the vector layers:
Testo
Formattazione
Contorno
Sfondo
Ombra
Posizionamento
Visualizzazione
Let us see how the new menus can be used for various vector layers.
Labeling point layers
Start QGIS and load a vector point layer. Activate the layer in the legend and click on the Layer Labeling Options icon in the QGIS toolbar menu.
The first step is to activate the Label this layer with checkbox and select an attribute column to use for labeling. Click if you want to define labels based on expressions - See labeling_with_expressions.
The following steps describe a simple labeling without using the Data defined override functions, which are situated next to the drop-down menus.
You can define the text style in the Text menu (see Figure_labels_1 ). Use the Type case option to influence the text rendering. You have the possibility to render the text ‘All uppercase’, ‘All lowercase’ or ‘Capitalize first letter’. Use the blend modes to create effects known from graphics programs (see blend_modes).
In the Formatting menu, you can define a character for a line break in the labels with the ‘Wrap on character’ function. Use the Formatted numbers option to format the numbers in an attribute table. Here, decimal places may be inserted. If you enable this option, three decimal places are initially set by default.
To create a buffer, just activate the Draw text buffer checkbox in the Buffer menu. The buffer color is variable. Here, you can also use blend modes (see blend_modes).
If the color buffer’s fill checkbox is activated, it will interact with partially transparent text and give mixed color transparency results. Turning off the buffer fill fixes that issue (except where the interior aspect of the buffer’s stroke intersects with the text’s fill) and also allows you to make outlined text.
In the Background menu, you can define with Size X and Size Y the shape of your background. Use Size type to insert an additional ‘Buffer’ into your background. The buffer size is set by default here. The background then consists of the buffer plus the background in Size X and Size Y. You can set a Rotation where you can choose between ‘Sync with label’, ‘Offset of label’ and ‘Fixed’. Using ‘Offset of label’ and ‘Fixed’, you can rotate the background. Define an Offset X,Y with X and Y values, and the background will be shifted. When applying Radius X,Y, the background gets rounded corners. Again, it is possible to mix the background with the underlying layers in the map canvas using the Blend mode (see blend_modes).
Use the Shadow menu for a user-defined Drop shadow. The drawing of the background is very variable. Choose between ‘Lowest label component’, ‘Text’, ‘Buffer’ and ‘Background’. The Offset angle depends on the orientation of the label. If you choose the Use global shadow checkbox, then the zero point of the angle is always oriented to the north and doesn’t depend on the orientation of the label. You can influence the appearance of the shadow with the Blur radius. The higher the number, the softer the shadows. The appearance of the drop shadow can also be altered by choosing a blend mode (see blend_modes).
Choose the Placement menu for the label placement and the labeling priority. Using the Offset from point setting, you now have the option to use Quadrants to place your label. Additionally, you can alter the angle of the label placement with the Rotation setting. Thus, a placement in a certain quadrant with a certain rotation is possible. In the priority section you can define with which priority the labels are rendered. It interacts with labels of the other vector layers in the map canvas. If there are labels from different layers in the same location then the label with the higher priority will be displayed and the other will be left out.
In the Rendering menu, you can define label and feature options. Under Label options, you find the scale-based visibility setting now. You can prevent QGIS from rendering only selected labels with the Show all labels for this layer (including colliding labels) checkbox. Under Feature options, you can define whether every part of a multipart feature is to be labeled. It’s possible to define whether the number of features to be labeled is limited and to Discourage labels from covering features.
Figure Labels 1:
Labeling line layers
The first step is to activate the Label this layer checkbox in the Label settings tab and select an attribute column to use for labeling. Click if you want to define labels based on expressions - See labeling_with_expressions.
After that, you can define the text style in the Text menu. Here, you can use the same settings as for point layers.
Also, in the Formatting menu, the same settings as for point layers are possible.
The Buffer menu has the same functions as described in section labeling_point_layers.
The Background menu has the same entries as described in section labeling_point_layers.
Also, the Shadow menu has the same entries as described in section labeling_point_layers.
In the Placement menu, you find special settings for line layers. The label can be placed Parallel, Curved or Horizontal. With the Parallel and Curved option, you can define the position Above line, On line and Below line. It’s possible to select several options at once. In that case, QGIS will look for the optimal position of the label. Remember that here you can also use the line orientation for the position of the label. Additionally, you can define a Maximum angle between curved characters when selecting the Curved option (see Figure_labels_2 ).
You can set up a minimum distance for repeating labels. Distance can be in mm or in map units.
Some Placement setup will display more options, for example, Curved and Parallel Placements will allow the user to set up the position of the label (above, below or on the line), distance from the line and for Curved, the user can also setup inside/outside max angle between curved label. As for point vector layers you have the possibility to define a Priority for the labels.
The Rendering menu has nearly the same entries as for point layers. In the Feature options, you can now Suppress labeling of features smaller than.
Figure Labels 2:
Labeling polygon layers
The first step is to activate the Label this layer checkbox and select an attribute column to use for labeling. Click if you want to define labels based on expressions - See labeling_with_expressions.
In the Text menu, define the text style. The entries are the same as for point and line layers.
The Formatting menu allows you to format multiple lines, also similar to the cases of point and line layers.
As with point and line layers, you can create a text buffer in the Buffer menu.
Use the Background menu to create a complex user-defined background for the polygon layer. You can use the menu also as with the point and line layers.
The entries in the Shadow menu are the same as for point and line layers.
In the Placement menu, you find special settings for polygon layers (see Figure_labels_3). Offset from centroid, Horizontal (slow), Around centroid, Free and Using perimeter are possible.
In the Offset from centroid settings, you can specify if the centroid is of the visible polygon or whole polygon. That means that either the centroid is used for the polygon you can see on the map or the centroid is determined for the whole polygon, no matter if you can see the whole feature on the map. You can place your label with the quadrants here, and define offset and rotation. The Around centroid setting makes it possible to place the label around the centroid with a certain distance. Again, you can define visible polygon or whole polygon for the centroid. With the Using perimeter settings, you can define a position and a distance for the label. For the position, Above line, On line, Below line and Line orientation dependent position are possible.
Related to the choice of Label Placement, several options will appear. As for Point Placement you can choose the distance for the polygon outline, repeat the label around the polygon perimeter.
As for point and line vector layers you have the possibility to define a Priority for the polygon vector layer.
The entries in the Rendering menu are the same as for line layers. You can also use Suppress labeling of features smaller than in the Feature options.
Figure Labels 3:
Define labels based on expressions
QGIS allows to use expressions to label features. Just click the icon in the Labels menu of the properties dialog. In figure_labels_4 you see a sample expression to label the alaska regions with name and area size, based on the field ‘NAME_2’, some descriptive text and the function ‘$area()’ in combination with ‘format_number()’ to make it look nicer.
Figure Labels 4:
Expression based labeling is easy to work with. All you have to take care of is, that you need to combine all elements (strings, fields and functions) with a string concatenation sign ‘||’ and that fields a written in “double quotes” and strings in ‘single quotes’. Let’s have a look at some examples:
# label based on two fields 'name' and 'place' with a comma as separater
"name" || ', ' || "place"
-> John Smith, Paris
# label based on two fields 'name' and 'place' separated by comma
'My name is ' || "name" || 'and I live in ' || "place"
-> My name is John Smith and I live in Paris
# label based on two fields 'name' and 'place' with a descriptive text
# and a line break (\n)
'My name is ' || "name" || '\nI live in ' || "place"
-> My name is John Smith
I live in Paris
# create a multi-line label based on a field and the $area function
# to show the place name and its area size based on unit meter.
'The area of ' || "place" || 'has a size of ' || $area || 'm²'
-> The area of Paris has a size of 105000000 m²
# create a CASE ELSE condition. If the population value in field
# population is <= 50000 it is a town, otherwise a city.
'This place is a ' || CASE WHEN "population <= 50000" THEN 'town' ELSE 'city' END
-> This place is a town
As you can see in the expression builder, you have hundreds of functions available to create simple and very complex expressions to label your data in QGIS. See Expressions chapter for more information and examples on expressions.
Using data-defined override for labeling
With the data-defined override functions, the settings for the labeling are overridden by entries in the attribute table. You can activate and deactivate the function with the right-mouse button. Hover over the symbol and you see the information about the data-defined override, including the current definition field. We now describe an example using the data-defined override function for the Move label function (see figure_labels_5 ).
Fai zoom su un lago
Figure Labels 5:
Figure Labels 6:
Within the Fields menu, the field attributes of the selected dataset can be manipulated. The buttons New Column and Delete Column can be used when the dataset is in Editing mode.
Widget modifica
Figure Fields 1:
Nel menu Campi hai la possibilità di usare un widget per la modifica. In questo modo puoi specificare un tipo paricolare di colonna in funzione dei dati che contiene. Se clicchi sul pulsante [modifica contenuto] si aprirà una finestra di dialogo in cui puoi scegliere fra diversi widget:
Casella di controllo: mostra una casella di controllo: se spunti la casella allora l’attributo verrà aggiunto alla colonna, altrimenti verrà rimosso.
Classificazione: visualizza un menu a tendina con i valori usati per la classificazione se hai scelto ‘Categorizzato’ come tipo di visualizzatore nel menu Stile delle proprietà del vettore.
Colore virtualizza un pulsante che permette di scegliere un colore da un finestra Selettore di colore
Enumerazione: apre un menu a tendina con i valori che possono essere usati nelle tipologie delle colonne. Attualmente questa funzione è supportata solo da PostgreSQL.
Nome file: seleziona un file dal tuo computer grazie alla finestra dedicata.
Nascosto: rende invisibile la colonna, quindi non potrai vederne il contenuto.
Foto: campo che contiene un percorso ad una foto. Puoi specificare sia la larghezza che l’altezza del campo.
Intervallo: ti permette di impostare dei valori di un preciso intervallo numerico. Il widget può apparire come un cursore o come un campo modificabile.
** Text Edit ** (default): apre un campo di modifica testo che consente di modificare un testo semplice o più righe da utilizzare. Se si sceglie più linee si può anche scegliere i contenuti html.
Valori univoci: puoi selezionare uno dei valori già presenti nella tabella degli attributi. Se la voce ‘Modificabile’ è attiva, allora comparirà anche una casella con l’autocompletamento, altrimenti verrà visualizzato un menu a tendina.
Generatore UUID: genera un campo UUID (Universally Unique Idetifiers) di sola lettura, se il campo è vuoto.
Mappa valori: un menu a tendina con oggetti predefiniti. Puoi associare una descrizione ad valore: nel menu a tendina potrai scegliere fra le varie descrizioni, ma nella tabella degli attributi verrà scritto il valore associato. Puoi specificare i valori manualmente oppure caricarli da un file CSV.
Vista web: il campo contiene un URL di una pagina internet. Puoi aggiustare la larghezza e l’altezza.
Nota
QGIS has an advanced ‘hidden’ option to define your own field widget using python and add it to this impressive list of widgets. It is tricky but it is very well explained in following excellent blog that explains how to create a real time validation widget that can be used like described widgets. See http://blog.vitu.ch/10142013-1847/write-your-own-qgis-form-elements
With the Attribute editor layout, you can now define built-in forms (see figure_fields_2). This is usefull for data entry jobs or to identify objects using the option auto open form when you have objects with many attributes. You can create an editor with several tabs and named groups to present the attribute fields.
Choose ‘Drag and drop designer’ and an attribute column. Use the icon to create a category to insert a tab or a named group (see figure_fields_3). When creating a new category, QGIS will insert a new tab or named group for the category in the built-in form. The next step will be to assign the relevant fields to a selected category with the icon. You can create more categories and use the same fields again.
Other options in the dialog are ‘Autogenerate’ and ‘Provide ui-file’.
QGIS dialogs can have a Python function that is called when the dialog is opened. Use this function to add extra logic to your dialogs. An example is (in module MyForms.py):
def open(dialog,layer,feature):
geom = feature.geometry()
control = dialog.findChild(QWidged,"My line edit")
Reference in Python Init Function like so: MyForms.open
MyForms.py must live on PYTHONPATH, in .qgis2/python, or inside the project folder.
Figure Fields 2:
Figure Fields 3:
Usa questo menu per gestire le impostazioni principali dei vettori. Hai a disposizione diverse opzioni:
Informazioni del layer
Cambia il nome visualizzato del vettore in visualizzato come
Specifica la Sorgente layer del vettore
Specifica la Codifica sorgente dati per abilitare codifiche specifiche e per poter leggere il file
Sistema di Riferimento
Specifica il sistema di riferimento delle coordinate. Qui puoi vedere o cambiare la proiezione del vettore.
Crea indice spaziale (solo per formati supportati da OGR)
Aggiorna estensione del vettore
Vedi o cambia la proiezione di un vettore cliccando su Specifica ...
Feature subset
Figure General 1:
QGIS 2.2 introduces support for on-the-fly feature generalisation. This can improve rendering times when drawing many complex features at small scales. This feature can be enabled or disabled in the layer settings using the Simplify geometry option. There is also a new global setting that enables generalisation by default for newly added layers (see section Opzioni dell’interfaccia grafica (GUI)). Note: Feature generalisation may introduce artefacts into your rendered output in some cases. These may include slivers between polygons and inaccurate rendering when using offset-based symbol layers.
This menu is specifically created for Map Tips. It includes a new feature: Map Tip display text in HTML. While you can still choose a Field to be displayed when hovering over a feature on the map, it is now possible to insert HTML code that creates a complex display when hovering over a feature. To activate Map Tips, select the menu option View ‣ MapTips. Figure Display 1 shows an example of HTML code.
Figure Display 1:
Figure Display 2:
QGIS provides the ability to perform an action based on the attributes of a feature. This can be used to perform any number of actions, for example, running a program with arguments built from the attributes of a feature or passing parameters to a web reporting tool.
Figure Actions 1:
Le azioni sono utili quando vuoi avviare un’applicazione esterna oppure aprire una pagina web sulla base di uno o più valori associati al vettore. Ci sono sei tipologie di azioni che puoi usare nel seguente modo:
Le azioni Generic, Mac, Windows e Unix avviano un processo esterno.
Le azioni python eseguono un’espressione python,
Le azioni generic e python sono visibili ovunque.
Le azioni Mac, Windows e Unix sono visibili solo sulle rispettive piattaforme (cioè puoi definire le azioni, ma sari in grado di vedere i risultati solamente sulla piattaforma dalla quale è stato lanciato l’editor).
Ci sono diversi esempi presenti nella finestra di dialogo. Puoi caricarli cliccando su [Aggiungi azioni predefinite]. Un esempio è eseguire una ricerca sul web basata su un valore presente nella tabella degli attributi. Di seguito una spiegazione.
Defining Actions
Puoi definire le azioni dalla finestra di dialogo Proprietà layer. Per definire un’azione, apri questa finestra e clicca sul menu Azioni. Dal sottomenu Proprietà azione scegli ‘Generico’ come tipo e inserisci un nome per l’azione. L’azione deve contenere il nome dell’applicazione che verrà eseguita quando lancerai l’azione. Puoi aggiungere uno o più campi come argomenti per l’applicazione. L’azione inizierà sempre con il carattere % seguito dal nome del campo che verrà sostituito dal valore del campo stesso. I caratteri speciali %% verranno sostituiti dal valore del campo che hai scelto dalla tabella degli attributi (vedi using_actions). Puoi usare le doppie virgolette, “ per raggruppare il testo in un singolo argomento per il programma, script o comando. Le doppie virgolette saranno ignorate se precedute dal carattere \.
If you have field names that are substrings of other field names (e.g., col1 and col10), you should indicate that by surrounding the field name (and the % character) with square brackets (e.g., [%col10]). This will prevent the %col10 field name from being mistaken for the %col1 field name with a 0 on the end. The brackets will be removed by QGIS when it substitutes in the value of the field. If you want the substituted field to be surrounded by square brackets, use a second set like this: [[%col10]].
Using the Identify Features tool, you can open the Identify Results dialog. It includes a (Derived) item that contains information relevant to the layer type. The values in this item can be accessed in a similar way to the other fields by preceeding the derived field name with (Derived).. For example, a point layer has an X and Y field, and the values of these fields can be used in the action with %(Derived).X and %(Derived).Y. The derived attributes are only available from the Identify Results dialog box, not the Attribute Table dialog box.
Due esempi di azioni sono di seguito indicati:
Nel primo esempio, verrà lanciato il browser konqueror che aprirà un URL. L’URL crea una ricerca Google sul valore del campo nam nel vettore. Il programma o lo script richiamato dall’azione deve essere nel path delle variabili d’ambiente altrimenti dovrai specificare il percorso completo del programma. Il primo esempio infatti è accessibile anche con /opt/kde3/bin/konqueror http://www.google.com/search?q=%nam. In questo modo sei sicuro che l’applicazione konqueror verrà eseguita quando si richiama l’azione..
Nel secondo esempio viene usata la notazione %% che non richiede l’indicazione di un particolare campo. Quando richiami l’azione, il %% sarà rimpiazzato dal valore selezionato sia nella finestra Informazioni risultati sia nella tabella degli attributi.
Using Actions
Actions can be invoked from either the Identify Results dialog, an Attribute Table dialog or from Run Feature Action (recall that these dialogs can be opened by clicking Identify Features or Open Attribute Table or Run Feature Action). To invoke an action, right click on the record and choose the action from the pop-up menu. Actions are listed in the popup menu by the name you assigned when defining the action. Click on the action you wish to invoke.
Se stai richiamando un’azione che usa l’annotazione %%, fai click con il tasto destro sul valore del campo nella finestra Informazioni risultati oppure dalla finestra Tabella attributi e scegli l’applicazione o lo script da assegnare.
Here is another example that pulls data out of a vector layer and inserts it into a file using bash and the echo command (so it will only work on or perhaps ). The layer in question has fields for a species name taxon_name, latitude lat and longitude long. We would like to be able to make a spatial selection of localities and export these field values to a text file for the selected record (shown in yellow in the QGIS map area). Here is the action to achieve this:
bash -c "echo \"%taxon_name %lat %long\" >> /tmp/species_localities.txt"
Selezionando solo alcune posizioni, l’esecuzione dell’azione precedente genera un file di output fatto così:
Acacia mearnsii -34.0800000000 150.0800000000
Acacia mearnsii -34.9000000000 150.1200000000
Acacia mearnsii -35.2200000000 149.9300000000
Acacia mearnsii -32.2700000000 150.4100000000
Come esercizio puoi creare un’azione che lancia una ricerca su Google in base al vettore lakes. Prima di tutto devi impostare l’URL necessario per eseguire una ricerca basata su una parola chiave. Puoi copiare facilmente l’espressione facendo una ricerca semplice dalla pagina di Google. La pagina dei risultati avrà un indirizzo, visibile nella barra indirizzi del browser, del tipo: http://google.com/search?q=qgis, in cui QGIS è la parola ricercata. Ora puoi procedere:
Assicurarti di aver caricato il vettore lakes.
Open the Layer Properties dialog by double-clicking on the layer in the legend, or right-click and choose Properties from the pop-up menu.
Clicca sul menu Azioni.
Inserisci un nome descrittivo per l’azione, ad esempio Ricerca Google.
Devi fornire il nome del programma esterno, in questo caso Firefox. Se il programma non è presente nel tuo path, devi inserire il path assoluto.
Dopo il nome dell’applicazione esterna, aggiungi l’URL della ricerca di Google, senza includere il termine della ricerca:http://google.com/search?q=
A questo punto il testo nel campo Azioni dovrebbe apparire così: firefox http://google.com/search?q=
Clicca sul menu a tendina che contiene i nomi dei campi dell vettore lakes, posizionato immediatamente a sinistra del pulsante [Inserisci campo].
Dal menu a tendina, seleziona ‘NAMES’ e clicca su [Inserisci campo].
Il testo dell’azione dovrebbe ora apparire come segue:
firefox http://google.com/search?q=%NAMES
Per concludere questa azione, clicca sul pulsante [Aggiungi alla lista di azioni].
Questo ultimo passo completa l’azione che è ora pronta per essere usata. Il testo finale dell’azione dovrebbe apparire così:
firefox http://google.com/search?q=%NAMES
A questo punto puoi usare l’azione. Chiudi la finestra Proprietà layer e usa lo zoom su un’area a scelta. Assicurati che il vettore lakes sia attivo ed identifica con l’apposito strumento un lago qualsiasi. Nella finestra risultante dovrebbe essere visibile l’azione:
Figure Actions 2:
Cliccando sull’azione, verrà lanciato Firefox all’URL http://www.google.com/search?q=Tustumena. Puoi anche aggiungere altri campi all’azione, aggiungendo un + alla fine della stringa che definisce l’azione, selezionando quindi un altro campo e cliccando sul pulsante [Inserisci campo]. Nel nostro esempio non c’è alcun altro campo sul quale avrebbe senso fare una ricerca.
Puoi definire più di un’azione per ogni vettore, ognuna delle quali verrà mostrata nella finestra Informazioni sui risultati.
Puoi creare tantissimi tipi di azione. Per esempio se hai un vettore di punti che fa riferimento alle posizioni dove sono state scattate foto o immagini, insieme al nome stesso del file, puoi creare un’azione per avviare un programma che visualizzerà l’immagine. Puoi usare le azioni anche per lanciare report sul web per uno o più campi della tabella degli attributi, definendole allo stesso modo dell’esempio per la ricerca con Google.
Ci sono esempi anche molto più complicati, per esempio usando le azioni Python.
Normalmente quando usi un’azione per aprire un file con un’applicazione esterna, puoi usare un path assoluto o relativo. Nel secondo caso, il path è relativo alla posizione dell’eseguibile dell’applicazione esterna. Ma come si fa se devi usare un path relativo al vettore selezionato (se è un file, come uno shapefile o Spatialite)? Ecco il trucco:
command = "firefox";
imagerelpath = "images_test/test_image.jpg";
layer = qgis.utils.iface.activeLayer();
import os.path;
layerpath = layer.source() if layer.providerType() == 'ogr'
else (qgis.core.QgsDataSourceURI(layer.source()).database()
if layer.providerType() == 'spatialite' else None);
path = os.path.dirname(str(layerpath));
image = os.path.join(path,imagerelpath);
import subprocess;
subprocess.Popen( [command, image ] );
Ricordati che l’azione è del tipo Python, quindi devi cambiare le variabili command e imagerelpath.
E se il percorso relativo deve essere relativo al file di progetto (salvato)? Il codice per l’azione Python diventa:
command="firefox";
imagerelpath="images/test_image.jpg";
projectpath=qgis.core.QgsProject.instance().fileName();
import os.path; path=os.path.dirname(str(projectpath)) if projectpath != '' else None;
image=os.path.join(path, imagerelpath);
import subprocess;
subprocess.Popen( [command, image ] );
Un altro esempio di azione python è quello che ti permette di aggiungere nuovi layer al progetto. In questo esempio aggiungeremo sia un vettore che un raster. Il nome dei file da aggiungere al progetto e il nome da assegnare ai layer è specificato dai dati (filename e layname sono nomi di colonne della tabella dagli attributi del vettore dove l’azione è stata creata):
qgis.utils.iface.addVectorLayer('/yourpath/[% "filename" %].shp','[% "layername" %]',
'ogr')
Per aggiungere un raster (in questo caso un’immagine TIF), diventa:
qgis.utils.iface.addRasterLayer('/yourpath/[% "filename" %].tif','[% "layername" %]
')
The Joins menu allows you to join a loaded attribute table to a loaded vector layer. After clicking , the Add vector join dialog appears. As key columns, you have to define a join layer you want to connect with the target vector layer. Then, you have to specify the join field that is common to both the join layer and the target layer. Now you can also specify a subset of fields from the joined layer based on the checkbox Choose which fields are joined. As a result of the join, all information from the join layer and the target layer are displayed in the attribute table of the target layer as joined information. If you specified a subset of fields only these fields are displayed in the attribute table of the target layer.
QGIS currently has support for joining non-spatial table formats supported by OGR (e.g., CSV, DBF and Excel), delimited text and the PostgreSQL provider (see figure_joins_1).
Figure Joins 1:
Inoltre, la finestra di dialogo aggiungi vettore da unire ti permette di:
Il menu Diagrammi permette di sovrapporre diagrammi a un vettore (figura figure_diagrams_1).
The current core implementation of diagrams provides support for pie charts, text diagrams and histograms.
The menu is divided into four tabs: Appearance, Size, Postion and Options.
In the cases of the text diagram and pie chart, text values of different data columns are displayed one below the other with a circle or a box and dividers. In the Size tab, diagram size is based on a fixed size or on linear scaling according to a classification attribute. The placement of the diagrams, which is done in the Position tab, interacts with the new labeling, so position conflicts between diagrams and labels are detected and solved. In addition, chart positions can be fixed manually.
Figure Diagrams 1:
We will demonstrate an example and overlay on the Alaska boundary layer a text diagram showing temperature data from a climate vector layer. Both vector layers are part of the QGIS sample dataset (see section Dati campione).
Fai doppio click sul vettore climate nella legenda per aprire la finestra di dialogo Proprietà layer.
Nella scheda Aspetto scegli un blu chiaro come colore di sfondo e nella scheda Dimensione imposta 18 mm come dimensione fissa.
Nella scheda Posizione scegli ‘Intorno al punto’ come posizionamento.
Clicca su [OK].
Figure Diagrams 2:
Ricordati che puoi usare anche l’opzione Posizione definita da attributo per posizionare i diagrammi. Inoltre puoi anche impostare la visibilità dei diagrammi in funzione di determinate scale dalla scheda Aspetto.
The size and the attributes can also be an expression. Use the button to add an expression. See Expressions chapter for more information and example.
The Metadata menu consists of Description, Attribution, MetadataURL and Properties sections.
In the Properties section, you get general information about the layer, including specifics about the type and location, number of features, feature type, and editing capabilities. The Extents table provides you with layer extent information and the Layer Spatial Reference System, which is information about the CRS of the layer. This is a quick way to get information about the layer.
Additionally, you can add or edit a title and abstract for the layer in the Description section. It’s also possible to define a Keyword list here. These keyword lists can be used in a metadata catalogue. If you want to use a title from an XML metadata file, you have to fill in a link in the DataUrl field. Use Attribution to get attribute data from an XML metadata catalogue. In MetadataUrl, you can define the general path to the XML metadata catalogue. This information will be saved in the QGIS project file for subsequent sessions and will be used for QGIS server.
Figure Metadata 1: