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

Janela de Propriedades de Vetor

The Layer Properties dialog for a vector layer provides general settings to manage appearance of layer features in the map (symbology, labeling, diagrams), interaction with the mouse (actions, map tips, form design). It also provides information about the layer.

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.


Switch quickly between different layer representations

Using the Styles ‣ Add combobox at the bottom of the Layer Properties dialog, you can save as many combinations of layer properties settings (symbology, labeling, diagram, fields form, actions...) as you want. Then, simply switch between styles from the context menu of the layer in Layers Panel to automatically get different representations of your data.

Menu Geral

general Use this menu to make general settings for the vector layer. There are several options available:

Informação da Camada

  • Alterar o nome de exibição da camada em: guilabel: apresentado como

  • Define o: guilabel: source Camada da camada de vetor

  • Defina o: guilabel: codificação de fonte de dados para definir opções específicas do provedor e ser capaz de ler o arquivo

Sistema de Referência de Coordenadas

  • : guilabel: Especificar o sistema de referência de coordenadas. Aqui, você pode visualizar ou alterar a projeção da camada vetorial específica.

  • Crie um índice espacial (somente para formatos OGR suportados)

  • : guilabel: informação Atualizar Extensões para uma camada

  • Exibir ou alterar a projeção da camada de vetor específico, clicando em: guilabel: Especifique ...

Scale dependent visibility

You can set the Maximum (inclusive) and Minimum (exclusive) scale, defining a range of scale in which features will be visible. Out of this range, they are hidden. The mapIdentification Set to current canvas scale button helps you use the current map canvas scale as boundary of the range visibility.

Figure Vector General 1:


General menu in vector layers properties dialog

Query Builder

Under the Provider Feature Filter frame, the Query Builder allows you to define a subset of the features in the layer using a SQL-like WHERE clause and to display the result in the main window. As long as the query is active, only the features corresponding to its result are available in the project. The query result can be saved as a new vector layer.

The Query Builder is accessible through the eponym term at the bottom of the General menu in the Layer Properties. Under Feature subset, click on the [Query Builder] button to open the Query builder. For example, if you have a regions layer with a TYPE_2 field, you could select only regions that are borough in the Provider specific filter expression box of the Query Builder. Figure_vector_general_2 shows an example of the Query Builder populated with the regions.shp layer from the QGIS sample data. The Fields, Values and Operators sections help you to construct the SQL-like query.

Figure Vector General 2:


Query Builder

The Fields list contains all attribute columns of the attribute table to be searched. To add an attribute column to the SQL WHERE clause field, double click its name in the Fields list. Generally, you can use the various fields, values and operators to construct the query, or you can just type it into the SQL box.

The Values list lists the values of an attribute table. To list all possible values of an attribute, select the attribute in the Fields list and click the [all] button. To list the first 25 unique values of an attribute column, select the attribute column in the Fields list and click the [Sample] button. To add a value to the SQL WHERE clause field, double click its name in the Values list.

The Operators section contains all usable operators. To add an operator to the SQL WHERE clause field, click the appropriate button. Relational operators ( = , > , ...), string comparison operator (LIKE), and logical operators (AND, OR, ...) are available.

The [Test] button shows a message box with the number of features satisfying the current query, which is useful in the process of query construction. The [Clear] button clears the text in the SQL WHERE clause text field. The [OK] button closes the window and selects the features satisfying the query. The [Cancel] button closes the window without changing the current selection.

QGIS treats the resulting subset acts as if it where the entire layer. For example if you applied the filter above for ‘Borough’, you can not display, query, save or edit Anchorage, because that is a ‘Municipality’ and therefore not part of the subset.

The only exception is that unless your layer is part of a database, using a subset will prevent you from editing the layer.

Menu Estilo

The Style menu provides you with a comprehensive tool for rendering and symbolizing your vector data. You can use tools that are common to all vector data, as well as special symbolizing tools that were designed for the different kinds of vector data. However all types share the following dialog structure: in the upper part, you have a widget that helps you prepare the classification and the symbol to use for features and at the bottom the Renderização da camada widget.


Exportar simbologia vetorial

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

Features rendering

The renderer is responsible for drawing a feature together with the correct symbol. Regardless layer geometry type, there are four common types of renderers: single symbol, categorized, graduated and rule-based. For point layers, there are a point displacement and a heatmap renderers available while polygon layers can also be rendered with the inverted renderer.

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 each data type (points, lines and polygons), vector symbol layer types are available. Depending on the chosen renderer, the dialog provides different additional sections.


Se você alterar o tipo de processador ao definir o estilo de uma camada de vetor as configurações feitas para o símbolo serão mantidas. Esteja ciente de que este procedimento só funciona para uma mudança. Se você repetir a alteração do tipo de renderizador as configurações para o símbolo irão se perder.

Single Symbol Renderer

The singleSymbol Single Symbol Renderer is used to render all features of the layer using a single user-defined symbol. See The symbol Selector for further information about symbol representation.

Figure Symbology 1:


Single symbol line properties


edit symbol directly from layer panel

If in your Layers Panel you have layers with categories defined through categorized, graduated or rule-based style mode, you can quickly change the fill color of the symbol of the categories by right-clicking on a category and choose the color you prefer from a colorWheel color wheel menu. Right-clicking on a category will also give you access to the options Hide all items, Show all items and Edit symbol.

Categorized Renderer

The categorizedSymbol Categorized Renderer is used to render all features from a layer, using an user-defined symbol whose aspect reflects the value of a selected feature’s attribute. The Categorized menu allows you to select:

  • The attribute (using the Column listbox or the expressionEditorOpen Set column expression function, see Expressões chapter)
  • The symbol (using the The symbol Selector dialog) which will be used as default for each class
  • The range of colors (using the Color ramp listbox) from which color applied to the symbol is selected

Then click on Classify button to create classes from the distinct value of the attribute column. Each class can be disabled unchecking the checkbox at the left of the class name.

To change symbol, value and/or label of the class, just double click on the item you want to change.

Right-click shows a contextual menu to Copy/Paste, Change color, Change transparency, Change output unit, Change symbol width.

The example in figure_symbology_2 shows the category rendering dialog used for the rivers layer of the QGIS sample dataset.

Figure Symbology 2:


Categorized Symbolizing options


Seleção e mudança de símbolos multiplos

A simbologia permite que você selecione vários símbolos e clique no direito para mudar de cor, transparência, tamanho ou largura das entradas selecionadas.


Match categories to symbol name

In the [Advanced] menu, under the classes, you can choose one of the two first actions to match symbol name to a category name in your classification. Matched to saved symbols match category name with a symbol name from your Style Manager. Match to symbols from file match category name to a symbol name from an external file.

Graduated Renderer

The graduatedSymbol Graduated Renderer is used to render all the features from a layer, using an user-defined symbol whose color or size reflects the assignment of a selected feature’s attribute to a class.

Like the Categorized Renderer, the Graduated Renderer allows you to define rotation and size scale from specified columns.

Also, analogous to the Categorized Renderer, it allows you to select:

  • The attribute (using the Column listbox or the expressionEditorOpen Set column expression function)
  • The symbol (using the Symbol selector dialog)
  • The legend format and the precision
  • The method to use to change the symbol: color or size
  • The colors (using the color Ramp list) if the color method is selected
  • The size (using the size domain and its unit

Then you can use the Histogram tab which shows an interactive histogram of the values from the assigned field or expression. Class breaks can be moved or added using the histogram widget.


You can use Statistical Summary panel to get more information on your vector layer. See Statistical Summary Panel.

Back to the Classes tab, 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:

  • Intervalo Igual: cada classe tem o mesmo tamanho (por exemplo, valores de 0 a 16 e com 4 classes, cada classe tem um tamanho 4);

  • Quantil: cada classe terá o mesmo número de elementos no interior (a idéia de uma caixa de plotagem);

  • Quebras naturais (Jenks): a variância dentro de cada classe é mínima, enquanto a variação entre as classes é máxima;

  • Desvio Padrão: classes são construídas de acordo com os valores do desvio padrão;

  • Pretty Breaks: Computes a sequence of about n+1 equally spaced nice values which cover the range of the values in x. The values are chosen so that they are 1, 2 or 5 times a power of 10. (based on pretty from the R statistical environment http://astrostatistics.psu.edu/datasets/R/html/base/html/pretty.html)

A caixa de listagem na parte central da lista do menu Estilo as classes juntamente com as suas faixas, etiquetas e símbolos que serão renderizados.

Click on Classify button to create classes using the chosen mode. Each classes can be disabled unchecking the checkbox at the left of the class name.

To change symbol, value and/or label of the class, just double click on the item you want to change.

Right-click shows a contextual menu to Copy/Paste, Change color, Change transparency, Change output unit, Change symbol width.

The example in figure_symbology_3 shows the graduated rendering dialog for the rivers layer of the QGIS sample dataset.

Figure Symbology 3:


Graduated Symbolizing options


Mapas Temáticos usando uma expressão

Categorized and graduated thematic maps can be created using the result of an expression. In the properties dialog for vector layers, the attribute chooser is extended with a expressionEditorOpen Set column expression function. So you don’t 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.

Proportional Symbol and Multivariate Analysis

Proportional Symbol and Multivariate Analysis are not rendering types available from the Style rendering drop-down list. However with the Size Assistant options applied over any of the previous rendering options, QGIS allows you to display your point and line data with such representation.

Creating proportional symbol

Proportional rendering is done by first applying to the layer the Single Symbol Renderer. Once you set the symbol, at the upper level of the symbol tree, the dataDefined Data-defined override button available beside Size or Width options (for point or line layers respectively) provides tool to create proportional symbology for the layer. An assistant is moreover accessible through the dataDefined menu to help you define size expression.

Figure Symbology 4:


Varying size assistant

The assistant lets you define:

  • The attribute to represent, using the Field listbox or the expressionEditorOpen Set column expression function (see Expressões)
  • the scale method of representation which can be ‘Flannery’, ‘Surface’ or ‘Radius’
  • The minimum and maximum size of the symbol
  • The range of values to represent: The down pointing arrow helps you fill automatically these fields with the minimum (or zero) and maximum values returned by the chosen attribute or the expression applied to your data.
  • An unique size to represent NULL values.

To the right side of the dialog, you can preview the features representation within a live-update widget. This representation is added to the layer tree in the layer legend and is also used to shape the layer representation in the print composer legend item.

The values presented in the varying size assistant above will set the size ‘Data-defined override’ with:

coalesce(scale_exp(Importance, 1, 20, 2, 10, 0.57), 1)

Creating multivariate analysis

A multivariate analysis rendering helps you evaluate the relationship between two or more variables e.g., one can be represented by a color ramp while the other is represented by a size.

The simplest way to create multivariate analysis in QGIS is to first apply a categorized or graduated rendering on a layer, using the same type of symbol for all the classes. Then, clicking on the symbol [Change] button above the classification frame, you get the The symbol Selector dialog from which, as seen above, you can activate and set the size assistant option either on size (for point layer) or width (for line layer).

Like the proportional symbol, the size-related symbol is added to the layer tree, at the top of the categorized or graduated classes symbols. And both representation are also available in the print composer legend item.

Rule-based rendering

The ruleBasedSymbol Rule-based Renderer is used to render all the features from a layer, using rule-based symbols whose aspect 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.

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 browseButton 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 on 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 Expressões). 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 matches. Since QGIS 2.8 the rules appear in a tree hierarchy in the map legend. Just double-click 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.

The example in figure_symbology_5 shows the rule-based rendering dialog for the rivers layer of the QGIS sample dataset.

Figure Symbology 5:


Rule-based Symbolizing options

Point displacement

The pointDisplacementSymbol 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 one center symbol or on several concentric circles.

Figure Symbology 6:


Point displacement dialog


You can still render features with other renderer like Single symbol, Graduated, Categorized or Rule-Based renderer using the Renderer drop-down list then the Renderer Settings... button.

Inverted Polygon

The invertedSymbol Inverted Polygon renderer allows user to define a symbol to fill in outside of the layer’s polygons. As above you can select subrenderers, namely Single symbol, Graduated, Categorized, Rule-Based or 2.5 D renderer.

Figure Symbology 7:


Inverted Polygon dialog


With the heatmapSymbol 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 and edit a color ramp for the heatmap style and use a slider for selecting a trade-off between render speed and quality. You can also define a maximum value limit and give a weight to points using a field or an expression. When adding or removing a feature the heatmap renderer updates the heatmap style automatically.

Figure Symbology 8:


Heatmap dialog

2.5 D

Using the 25dSymbol 2.5 D renderer it’s possible to create a 2.5 D effect on your layer’s features. You start by choosing a Height value (in map units). For that you can use a fixed value, one of your layer’s fields, or an expression. You also need to choose an Angle (in degrees) to recreate the viewer position (0° means west, growing in counter clock wise). Use advanced configuration options to set the Roof Color and Wall Color. If you would like to simulate solar radiation on the features walls, make sure to check the checkbox Shade walls based on aspect option. You can also simulate a shadow by setting a Color and Size (in map units).

Figure Symbology 9:


2.5 D dialog


Using 2.5 D effect with other renderers

Once you have finished setting the basic style on the 2.5 D renderer, you can convert this to another renderer (single, categorized, graduated). The 2.5 D effects will be kept and all other renderer specific options will be available for you to fine tune them (this way you can have for example categorized symbols with a nice 2.5 D representation or add some extra styling to your 2.5 D symbols). To make sure that the shadow and the “building” itself do not interfere with other nearby features, you may need to enable Symbols Levels ( Advanced ‣ Symbol levels...). The 2.5 D height and angle values are saved in the layer’s variables, so you can edit it afterwards in the variables tab of the layer’s properties dialog.

Renderização da camada

From the Style tab, you can also set some options that invariabily act on all features of the layer:

  • : guilabel: Transparência da camada | deslizante |: Você pode fazer a camada subjacente na tela do mapa visível com esta ferramenta. Use o controle deslizante para se adaptar a visibilidade de sua camada de vetor para suas necessidades. Você também pode fazer uma definição precisa do percentual de visibilidade no menu ao lado do controle deslizante.

  • Layer blending mode and Feature blending mode: You can achieve special rendering effects with these tools that you may previously only know from graphics programs. The pixels of your overlaying and underlaying layers are mixed through the settings described in Modos de Mistura.

  • Apply paint effects on all the layer features with the Draw Effects button.

  • Control feature rendering order allows you, using features attributes, to define the z-order in which they shall be rendered. Activate the checkbox and click on the browseButton button beside. You then get the Define Order dialog in which you:

    • choose a field or build an expression to apply to the layer features
    • set in which order the fetched features should be sorted, i.e. if you choose Ascending order, the features with lower value are rendered under those with upper value.
    • define when features returning NULL value should be rendered: first or last.

    You can add several rules of ordering. The first rule is applied to all the features in the layer, z-ordering them according to the value returned. Then, for each group of features with the same value (including those with NULL value) and thus same z-level, the next rule is applied to sort its items among them. And so on...

    Once the Define Order dialog is applied, a summary of the expression(s) used to control the layer rendering is retranscribed in the textbox beside checkbox Control feature rendering order option.

Figure Layer Rendering 1:


Layer rendering options

Other Settings

Symbols levels

For renderers that allow stacked symbol layers (only heatmap doesn’t) there is an option to control the rendering order of each symbol’s levels.

For most of the renderers, you can access the Symbols levels option by clicking the [Advanced] button below the saved symbols list and choosing Symbol levels. For the Rule-based rendering the option is directly available through [Symbols levels] button, while for Point displacement renderer the same button is inside the Rendering settings dialog.

To activate symbols levels, select the checkbox Enable symbol levels. Each row will show up a small sample of the combined symbol, its label and the individual symbols layer divided into columns with a number next to it. The numbers represent the rendering order level in which the symbol layer will be drawn. Lower values levels are drawn first, staying at the bottom, while higher values are drawn last, on top of the others.

Figure Symbols levels 1:


Symbol levels dialog


If symbols levels are deactivated, the complete symbols will be drawn according to their respective features order. Overlapping symbols will simply obfuscate to other below. Besides, similar symbols won’t “merge” with each other.

Figure Symbols levels 2:


Symbol levels activated (A) and deactivated (B) difference

Draw effects

In order to improve layer rendering and avoid (or at least reduce) the resort to other software for final rendering of maps, QGIS provides another powerful functionality: the paintEffects Draw Effects options, which adds paint effects for customizing the visualization of vector layers.

The option is available in the Layer Properties –> Style dialog, under the Layer rendering group (applying to the whole layer) or in symbol layer properties (applying to corresponding features). You can combine both usage.

Paint effects can be activated by checking the checkbox Draw effects option and clicking the paintEffects Customize effects button, that will open the Effect Properties Dialog (see figure_effects_1). The following effect types, with custom options are available:

  • Source: Draws the feature’s original style according to the configuration of the layer’s properties. The transparency of its style can be adjusted.

    Figure Effects 1:


    Draw Effects: Source dialog

  • Blur: Adds a blur effect on the vector layer. The options that someone can change are the Blur type (Stack or Gaussian blur), the strength and transparency of the blur effect.

    Figure Effects 2:


    Draw Effects: Blur dialog

  • Colorize: This effect can be used to make a version of the style using one single hue. The base will always be a grayscale version of the symbol and you can use the selectString Grayscale to select how to create it (options are: ‘lightness’, ‘luminosity’ and ‘average’). If checkbox Colorise is selected, it will be possible to mix another color and choose how strong it should be. You can also control the Brightness, contrast and saturation levels of the resulting symbol.

    Figure Effects 3:


    Draw Effects: Colorize dialog

  • Drop Shadow: Using this effect adds a shadow on the feature, which looks like adding an extra dimension. This effect can be customized by changing the offset degrees and radius, determining where the shadow shifts towards to and the proximity to the source object. Drop Shadow also has the option to change the blur radius, the transparency and the color of the effect.

    Figure Effects 4:


    Draw Effects: Drop Shadow dialog

  • Inner Shadow: This effect is similar to the Drop Shadow effect, but it adds the shadow effect on the inside of the edges of the feature. The available options for customization are the same as the Drop Shadow effect.

    Figure Effects 5:


    Draw Effects: Inner Shadow dialog

  • Inner Glow: Adds a glow effect inside the feature. This effect can be customized by adjusting the spread (width) of the glow, or the Blur radius. The latter specifies the proximity from the edge of the feature where you want any blurring to happen. Additionally, there are options to customize the color of the glow, with a single color or a color ramp.

    Figure Effects 6:


    Draw Effects: Inner Glow dialog

  • Outer Glow: This effect is similar to the Inner Glow effect, but it adds the glow effect on the outside of the edges of the feature. The available options for customization are the same as the Inner Glow effect.

    Figure Effects 7:


    Draw Effects: Outer Glow dialog

  • Transform: Adds the possibility of transforming the shape of the symbol. The first options available for customization are the Reflect horizontal and Reflect vertical, which actually create a reflection on the horizontal and/or vertical axes. The 4 other options are:

    • Shear: slants the feature along the x and/or y axis
    • Scale: enlarges or minimizes the feature along the x and/or y axis by the given percentage
    • Rotation: turns the feature around its center point
    • and Translate changes the position of the item based on a distance given on the x and/or the y axis.

    Figure Effects 8:


    Draw Effects: Transform dialog

There are some common options available for all draw effect types. Transparency and Blend mode options work similar to the ones described in Renderização da camada and can be used in all draw effects except for the transform one.

One or more draw effects can used at the same time. You activate/deactivate an effect using its checkbox in the effects list. You can change the selected effect type by using the selectString Effect type option. You can reorder the effects using arrowUp Move up and arrowDown Move down buttons, and also add/remove effects using the signPlus Add effect and signMinus Remove effect buttons.

There is also a selectString Draw mode option available for every draw effect, and you can choose whether to render and/or to modify the symbol. Effects render from top to bottom.’Render only’ mode means that the effect will be visible while the ‘Modify only’ mode means that the effect will not be visible but the changes that it applies will be passed to the next effect (the one immediately below). The ‘Render and Modify’ mode will make the effect visible and pass any changes to the next effect. If the effect is in the top of the effects list or if the immediately above effect is not in modify mode, then it will use the original source symbol from the layers properties (similar to source).

Menu Rótulos

The labeling Labels core application provides smart labeling for vector point, line and polygon layers, and only requires a few parameters. This application also supports on-the-fly transformed layers. The following menus are used to configure the labeling of vector layers:

  • Texto

  • Formatação

  • Buffer
  • Pano de fundo

  • Sombra

  • Localização

  • Desenhando

To label a layer start QGIS and load a vector layer. Activate the layer in the legend and click on the labeling Layer Labeling Options icon in the QGIS toolbar menu or activate the Labels tab in the layer properties dialog.

The first step is to choose the labeling method from the drop-down list. There are four options available:

  • No labels
  • Show labels for this layer
  • Rule-based labeling
  • and Discourage other labels from covering features in this layer: allows to set a layer as just an obstacle for other layer’s labels without rendering any labels of its own.

Select the Show labels for this layer option and then select an attribute column to use for labeling from the Label with drop-down list. Click expressionEditorOpen if you want to define labels based on expressions - See Define labels based on expressions.

The following steps describe simple labeling without using the Data defined override functions, which are situated next to the drop-down menus - see Using data-defined override for labeling for an use-case.

Text menu

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 Modos de Mistura to create effects known from graphics programs.

Figure Labels 1:


Smart labeling of vector point layers

Formatting menu

In the Formatting menu, you can define a character for a line break in the labels with the ‘Wrap on character’ function. You can format the Line Height and the alignment. For the latter typical values are available plus Follow label placement. When set to this mode, text alignment for labels will be dependent on the final placement of the label relative to the point. E.g., if the label is placed to the left of the point then the label will be right aligned, and if it is placed to the right of the point then the label will be left aligned.

For line vector layers you can include line directions symbols. There are options specifying the type of symbol and the symbol placement.

Use the checkbox 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.

Buffer menu

To create a buffer, just activate the checkbox Draw text buffer checkbox in the Buffer menu. The buffer color is variable. Here, you can also use blend modes. If the checkbox 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.

Background menu

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 Modos de Mistura).

Shadow menu

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

Placement menu

Choose the Placement menu for configuring label placement and labeling priority. Note that the placement options differ according to the type of vector layer, namely point, line or polygon.

Placement for point layers

With the radioButtonOn Cartographic placement mode, point labels are generated with best visual relationship with the point feature, following ideal cartographic placement rules. Labels can be placed at a set Distance either from the point feature itself or from the bounds of the symbol used to represent the feature. The latter option is especially useful when the symbol size isn’t fixed, e.g. if it’s set by a data defined size or when using different symbols in a categorized renderer.

By default, placements are prioritised in the following order:

  1. top right
  2. top left
  3. bottom right
  4. bottom left
  5. middle right
  6. middle left
  7. top, slightly right
  8. bottom, slightly left.

Placement priority can however be customized or set for an individual feature using a data defined list of prioritised positions. This also allows only certain placements to be used, so e.g. for coastal features you can prevent labels being placed over the land.

The radioButtonOn Around point setting places the label in an equal radius (set in Distance) circle around the feature. The placement of the label can even be constrained using the Quadrant option.

In the radioButtonOn Offset from point placement, labels are placed at a fixed offset from the point feature. You can select the Quadrant in which to place your label. You are also able to set the X and Y offset distances between the points and their labels and can alter the angle of the label placement with the Rotation setting. Thus, placement in a selected quadrant with a defined rotation is possible.

Placement for line layers

Label options for line layers include radioButtonOn Parallel, radioButtonOff Curved or radioButtonOff Horizontal. For the radioButtonOn Parallel and radioButtonOff Curved options, you can set the position to checkbox Above line, checkbox On line and checkbox Below line. It’s possible to select several options at once. In that case, QGIS will look for the optimal label position. For Parallel and curved placement 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 radioButtonOff Curved option (see Figure_labels_2 ).

For all three placement options you can set up a minimum distance for repeating labels. The distance can be in mm or in map units.

Figure Labels 2:


Smart labeling of vector line layers

Placement for polygon layers

You can choose one of the following options for placing labels in polygons: radioButtonOn Offset from centroid, radioButtonOff Horizontal (slow), radioButtonOff Around centroid, radioButtonOff Free and radioButtonOff Using perimeter.

In the radioButtonOn Offset from centroid settings you can specify if the centroid is of the radioButtonOn visible polygon or radioButtonOff 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 within a specific quadrant, and define offset and rotation. The radioButtonOff Around centroid setting places the label at a specified distance around the centroid. Again, you can define radioButtonOn visible polygon or radioButtonOff whole polygon for the centroid.

With the radioButtonOff Using perimeter settings, you can define a position and a distance for the label. For the position, checkbox Above line, checkbox On line, checkbox Below line and checkbox Line orientation dependent position are possible. You can specify the distance between the label and the polygon outline, as well as the repeat interval for the label.

Figure Labels 3:


Smart labeling of vector polygon layers

In the priority section you can define the priority with which labels are rendered for all three vector layer types (point, line, polygon). This placement option interact with labels of the other vector layers in the map canvas. If there are labels from different layers in the same location, the label with the higher priority will be displayed and the others will be left out.

Rendering menu

In the Rendering menu, you can tune when the labels can be rendered and their interaction with other labels and features.

Under Label options, you find the scale-based and the Pixel size-based visibility settings.

The Label z-index determines the order in which labels are rendered, as well in relation with other feature labels in the layer (using data-defined override expression), as with labels from other layers. Labels with a higher z-index are rendered on top of labels (from any layer) with lower z-index.

Additionally, the logic has been tweaked so that if 2 labels have matching z-indexes, then:

  • if they are from the same layer, the smaller label will be drawn above the larger label
  • if they are from different layers, the labels will be drawn in the same order as their layers themselves (ie respecting the order set in the map legend).

Note that this setting doesn’t make labels to be drawn below the features from other layers, it just controls the order in which labels are drawn on top of all the layer’s features.

While rendering labels and in order to display readable labels, QGIS automatically evaluates the position of the labels and can hide some of them in case of collision. You can however choose to checkbox Show all labels for this layer (including colliding labels) in order to manually fix their placement.

With data-defined expressions in Show label and Always Show you can fine tune which labels should be rendered.

Under Feature options, you can choose to label every part of a multi-part feature and limit the number of features to be labeled. Both line and polygon layers offer the option to set a minimum size for the features to be labeled, using Suppress labeling of features smaller than. For polygon features, you can also filter the labels to show according to whether they completely fit within the feature or not. For line features, you can choose to Merge connected lines to avoid duplicate labels, rendering a quite airy map in conjunction with the Distance or Repeat options in Placement tab.

From the Obstacles frame, you can manage the covering relation between labels and features. Activate the checkbox Discourage labels from covering features option to decide whether features of the layer should act as obstacles for any label (including labels from other features in the same layer). An obstacle is a feature QGIS tries as far as possible to not place labels over. Instead of the whole layer, you can define a subset of features to use as obstacles, using the dataDefined data-defined override control next to the option.

The slider priority control slider for obstacles allows you to make labels prefer to overlap features from certain layers rather than others. A Low weight obstacle priority means that features of the layer are less considered as obstacles and thus more likely to be covered by labels. This priority can also be data-defined, so that within the same layer, certain features are more likely to be covered than others.

For polygon layers, you can choose the type of obstacle features could be by minimising the labels placement:

  • over the feature’s interior: avoids placing labels over interior of polygon (prefers placing labels totally outside or just slightly inside polygon)
  • or over the feature’s boundary: avoids placing labels over boundary of polygon (prefers placing labels outside or completely inside the polygon). It can be e.g. useful for regional boundary layers, where the features cover an entire area. In this case it’s impossible to avoid placing labels within these features, and it looks much better to avoid placing them over the boundaries between features.

Define labels based on expressions

QGIS allows to use expressions to label features. Just click the expressionEditorOpen icon in the labeling 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:


Using expressions for labeling

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 function such as concat, + or ||. Be aware that in some situations (null or numeric value involved) not all of these tools will fit your need
  • strings are written in ‘single quotes’
  • fields are written in “double quotes” or without any quote.

Let’s have a look at some examples:

 # label based on two fields 'name' and 'place' with a comma as separator
 "name" || ', ' || "place"

 -> John Smith, Paris

 # label based on two fields 'name' and 'place' with other texts
 'My name is ' + "name" + 'and I live in ' + "place"
 'My name is ' || "name" || 'and I live in ' || "place"
 concat('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 other texts
 # combining different concatenation functions
 concat('My name is ', name, ' and I live in ' || place)

 -> My name is John Smith and I live in Paris
 -> My name is John Smith     # if the field 'place' is NULL

 # multi-line label based on two fields 'name' and 'place' with a descriptive text
 concat('My name is ', "name", '\n' , 'I live in ' , "place")
 -> My name is John Smith
    I live in Paris

 # label based on a field and the $area function
 # to show the place name and its rounded area size in a converted unit.
 'The area of ' || "place" || ' has a size of ' || round($area/10000) || ' ha'

 -> The area of Paris has a size of 10500 ha

 # create a CASE ELSE condition. If the population value in field
 # population is <= 50000 it is a town, otherwise a city.
 concat('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 Expressões 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 moveLabelMove label function (see figure_labels_5 ).

  1. Import lakes.shp from the QGIS sample dataset.
  2. Double-click the layer to open the Layer Properties. Click on Labels and Placement. Select radioButtonOn Offset from centroid.
  3. Look for the Data defined entries. Click the dataDefined icon to define the field type for the Coordinate. Choose ‘xlabel’ for X and ‘ylabel’ for Y. The icons are now highlighted in yellow.
  4. Zoom em um lago

  5. Set editable the layer using the toggleEditing Toggle Editing button.
  6. Go to the Label toolbar and click the moveLabel icon. Now you can shift the label manually to another position (see figure_labels_6). The new position of the label is saved in the ‘xlabel’ and ‘ylabel’ columns of the attribute table.

Figure Labels 5:


Labeling of vector polygon layers with data-defined override

Figure Labels 6:


Move labels

Rule-based labeling

With Rule-based labeling multiple label configurations can be defined and applied selectively on the base of expression filters, as in Rule-based rendering.

Rules can be set selecting the corresponding option at the top of the Labels panel (see figure_labels_7 ).

Figure Labels 7:


Rule based labeling panel

To create a rule, activate an existing row by double-clicking on it, or click on ‘+’ and click on the new rule. Within the panel you can set the filter expression and the related label configurations.

Figure Labels 8:


Rule settings

Menu campos

attributes Within the Fields menu, the field attributes of the selected dataset can be manipulated. The buttons newAttribute New Column and deleteAttribute Delete Column can be used when the dataset is in toggleEditing Editing mode.

Edição de Widget

Figure Fields 1:


Dialog to select an edit widget for an attribute column

No: guilabel: Menu Campos, você também encontrará uma coluna ** ferramenta de edição ** . Esta coluna pode ser utilizada para definir os valores ou variedade de valores que são permitidos para serem adicionados à coluna da tabela de atributos específicos. Se você clicar no ** [edit widget] ** botão, uma janela se abre, onde você pode definir diferentes elementos. Estes elementos são:

  • ** Caixa de seleção **: Exibe uma caixa de seleção e você pode definir qual atributo é adicionado na coluna quando a caixa de seleção é ativada ou não.

  • ** Classificação **: Exibe uma caixa de combinação com os valores utilizados para a classificação, se você tiver escolhido “valor único” como o tipo de lenda no: guilabel: Estilo menu da caixa de diálogo propriedade

  • Cor: Exibe um botão de cor permitindo que o usuário escolha uma cor na janela de diálogo de cor.

  • Date/Time: Displays a line field which can open a calendar widget to enter a date, a time or both. Column type must be text. You can select a custom format, pop-up a calendar, etc.
  • ** Enumeração **: Abre uma caixa de combinação com valores que podem ser usados ​​dentro no tipo de colunas. Atualmente é suportado apenas por provedores de PostgreSQL.

  • ** Nome do Arquivo **: Simplifica a seleção, adicionando uma janela de seleção de arquivos.

  • ** Oculto **: Uma coluna de atributo oculto é invisível. O usuário não é capaz de ver o seu conteúdo.

  • Foto: Campo que contém o nome do arquivo para a imagem. A largura e altura do campo podem ser definidos.

  • Tamanho: Permite definir valores numéricos de um tamanho específico. A edição do Widget pode ser um controle deslizante ou uma caixa de rotação.

  • Relation Reference: This widget lets you embed the feature form of the referenced layer on the feature form of the actual layer. See Creating one to many relations.
  • ** Edição de texto ** (padrão): Isto abre um campo de edição de texto que permite que o texto simples ou múltiplas linhas a sejam utilizados. Se você escolher várias linhas você também pode escolher o conteúdo html.

  • ** Valores únicos **: O usuário pode selecionar um dos valores já utilizados na tabela de atributos. Se editável é ativado, uma linha de edição é mostrada com suporte para autocompletar, caso contrário, uma caixa de combinação é utilizada.

  • ** Gerador UUID **: Gera um campo UUID (identificador exclusivo universal) somente para leitura, se vazio.

  • ** Mapa de Valor **: uma caixa de combinação com itens pré-definidos. O valor é armazenado no atributo, a descrição é mostrada na caixa de combinação. Você pode definir valores manualmente ou carregá-los a partir de uma camada ou um arquivo CSV.

  • Value Relation: Offers values from a related table in a combobox. You can select layer, key column and value column. Several options are available to change the standard behaviours: allow null value, order by value, allow multiple selections and use of autocompleter. The forms will display either a drop-down list or a line edit field when completer checkbox is enabled.
  • Webview: Campo que contém o nome do arquivo para a imagem. A largura e altura do campo podem ser definidos.


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


Relative Path in widgets

If the path which is selected with the file browser is located in the same directory as the .qgs project file or below, paths are converted to relative paths. This increases portability of a qgs project with multimedia information attached. This is enabled only for File Name, Photo and Web View at this moment.

With the Attribute editor layout, you can now define built-in forms (see figure_fields_2). This is useful 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 signPlus 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 arrowRight 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. The form code can be specified in three different ways:

  • load from the environment (for example in startup.py or from a plugin)
  • load from an external file, a file chooser will appear in that case to allow you to select a Python file from your filesystem
  • load from inline code, a Python editor will appear where you can directly type your form code

In all cases you must enter the name of the function that will be called (open in the example below).

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: open

Figure Fields 2:


Diálogo para criar categorias com o  ** |Editor Disposição Atributo **

Figure Fields 3:


Resulting built-in form with tabs and named groups

Menu Juntar

join The Joins menu allows you to join a loaded attribute table to a loaded vector layer. After clicking signPlus, 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 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:


Join an attribute table to an existing vector layer

Além disso, o diálogo juntar vetor adicionado permite:

  • checkbox Cache join layer in virtual memory
  • checkbox Create attribute index on the join field
  • checkbox Choose which fields are joined
  • Create a checkbox Custom field name prefix

Menu Diagramas

diagram The Diagrams menu allows you to add a graphic overlay to a vector layer (see figure_diagrams_1).

The current core implementation of diagrams provides support for:

  • pie charts, a circular statistical graphic divided into slices to illustrate numerical proportion. The arc length of each slice is proportional to the quantity it represents,
  • text diagrams, a horizontaly divided circle showing statistics values inside
  • and histograms.

For each type of diagram, the menu is divided into five tabs:


Attributes defines which variables to display in the diagram. Use signPlus add item button to select the desired fields into the ‘Assigned Attributes’ panel. Generated attributes with Expressões can also be used.

You can move up and down any row with click and drag, sorting how atributes are displayed. You can also change the label in the ‘Legend’ column or the attibute color by double-clicking the item.

This label is the default text displayed in the legend of the print composer or of the layer tree.

Figure Diagrams 1:


Vector properties dialog with diagram menu


Appearance defines how the diagram looks like. It provides general settings that do not interfere with the statistic values such as:

  • the graphic transparency, its outline width and color
  • the width of the bar in case of histogram
  • the circle background color in case of text diagram, and the font used for texts
  • the orientation of the left line of the first slice represented in pie chart. Note that slices are displayed clockwise.

In this menu, you can also manage the diagram visibility:

  • by removing diagrams that overlap others or Show all diagrams even if they overlap each other
  • by setting the scale visibility


Size is the main tab to set how the selected statistics are represented. The diagram size units can be ‘Map Units’ or ‘Millimeters’. You can use :

  • Fixed size, an unique size to represent the graphic of all the features, except when displaying histogram
  • or Scaled size, based on an expression using layer attributes.

Figure Diagrams 2:


Vector properties dialog with diagram menu, Size tab


Placement helps to define diagram position. According to the layer geometry type, it offers different options for the placement:

  • ‘Over the point’ or ‘Around the point’ for point geometry. The latter variable requires a radius to follow.
  • ‘Over the line’ or ‘Around the line’ for line geometry. Like point feature, the last variable requires a distance to respect and user can specify the diagram placement relative to the feature (‘above’, ‘on’ and/or ‘below’ the line) It’s possible to select several options at once. In that case, QGIS will look for the optimal position of the diagram. Remember that here you can also use the line orientation for the position of the diagram.
  • ‘Over the centroid’, ‘Around the centroid’ (with a distance set), ‘Perimeter’ and anywhere ‘Inside polygon’ are the options for polygon features.

The diagram can also be placed using feature data by filling the X and Y fields with an attribute of the feature.

The placement of the diagrams can interact with the labeling, so you can detect and solve position conflicts between diagrams and labels by setting the Priority slider or the z-index value.


The Options tab has settings only in case of histogram. You can choose whether the bar orientation should be ‘Up’, ‘Down’, ‘Right’ and ‘Left’.


Switch quickly between diagrams

Given that almost all the settings above are common to the different types of diagram, when designing your diagram, you can easily change the diagram type and check which one is more appropriate to your data without any loss.

Case Study

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 Amostra de Dados).

  1. First, click on the addOgrLayer Load Vector icon, browse to the QGIS sample dataset folder, and load the two vector shape layers alaska.shp and climate.shp.
  2. Dê um clique duplo na camada clima na legenda do mapa para abrir a aba de diálogo ‘Propriedades da camada `.

  3. Click on the Diagrams menu, activate checkbox Show diagrams for this layer, and from the Diagram type selectString combo box, select ‘Text diagram’.
  4. Na guia Aparência, escolhemos um azul claro como cor de fundo, e na guia Tamanho, montamos um tamanho fixo de 18 mm.

  5. Na guia Posição, a colocação pode ser definida como ‘em torno do ponto’.

  6. In the diagram, we want to display the values of the three columns T_F_JAN, T_F_JUL and T_F_MEAN. So, in the Attributes tab first select T_F_JAN and click the signPlus button, then repeat with T_F_JUL and finally T_F_MEAN.
  7. Now click [Apply] to display the diagram in the QGIS main window.
  8. You can adapt the chart size in the Size tab. Activate the radioButtonOn Scaled size and set the size of the diagrams on the basis of the maximum value of an attribute and the Size option. If the diagrams appear too small on the screen, you can activate the checkbox Increase size of small diagrams checkbox and define the minimum size of the diagrams.
  9. Change the attribute colors by double clicking on the color values in the Assigned attributes field. Figure_diagrams_3 gives an idea of the result.
  10. Finalmente, clique [Ok].

Figure Diagrams 3:


Diagram from temperature data overlayed on a map

Lembre-se que no: guilabel: guia ` Posição`, a | checkbox |: guilabel: Dados posição definida dos diagramas é possível. Aqui você pode usar atributos para definir a posição do diagrama. Você também pode definir a visibilidade dependente escala no: guilabel: guia ` Aparência`.

The size and the attributes can also be an expression. Use the expressionEditorOpen button to add an expression. See Expressões chapter for more information and example.

Menu de Ações

action 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:


Overview action dialog with some sample actions

Ações são úteis quando você frequentemente deseja executar uma aplicação externa ou visualizar uma página web com base em um ou mais valores em sua camada de vetor. Elas são divididas em seis tipos e pode ser usadas assim:

  • Iniciar ações genéricas, Mac, Windows e Unix em um processo externo.

  • Executar ações Python uma expressão Python.

  • Ações genéricas e Python são visíveis em toda parte.

  • Ações Mac, Windows e Unix são visíveis apenas na respectiva plataforma (ou seja, você pode definir ações de três “Editar” para abrir um editor e os usuários só podem ver e executar a ação “Editar” na sua plataforma para executar o editor) .

Existem vários exemplos incluídos na caixa de diálogo. Você pode carregá-los clicando no [Adicionar ações padrão]. Um exemplo é a realização de uma pesquisa com base em um valor de atributo. Este conceito é usado na discussão a seguir.

Defining Actions

Atributo ações são definidas a partir do vetor: guilabel: diálogo ‘Propriedades da Camada . Para: índice: `Definir uma Ação, abra o vetor: guilabel: ‘Propriedades da Camada ` de diálogo e clique no: guilabel: Menu` Ações . Vá para o: guilabel: `propriedades Ação. Selecione ‘genérico’ como tipo e fornecer um nome descritivo para a ação. A própria ação deve conter o nome do aplicativo que será executado quando a ação é invocado. Você pode adicionar um ou mais valores de campos de atributos como argumentos para a aplicação. Quando a ação é chamada, qualquer conjunto de caracteres que começam com um ``% ``, seguido do nome de um campo será substituído pelo valor desse campo. Os caracteres especiais: índice: %% será substituído pelo valor do campo que foi selecionado da tabela identificam resultados ou atributo (ver using_actions abaixo). Aspas duplas podem ser usadas ao texto do grupo em um único argumento para o programa, script ou comando. Aspas duplas serão ignoradas se precedido por uma barra invertida.

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

Dois: índice: ações exemplo são mostradas abaixo:

  • konqueror http://www.google.com/search?q=%nam
  • konqueror http://www.google.com/search?q=%%

No primeiro exemplo, o navegador Konqueror é consultado e passou uma URL para abrir. A URL executa uma pesquisa no Google sobre o valor do campo `` nam`` da nossa camada vetorial. Note-se que a aplicação ou script chamado pela ação devem estar no caminho, ou você deve fornecer o caminho completo. Para ter certeza, poderíamos reescrever o primeiro exemplo como: `` /opt/kde3/bin/konqueror http://www.google.com/search?q=%nam ``. Isto irá assegurar que a aplicação konqueror será executado quando a ação é consultada.

O segundo exemplo usa a notação % % , que não depende de um campo específico para o seu valor. Quando a ação é consultado, o % % será substituído pelo valor do campo selecionado na tabela de identificar resultados ou atributo.

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 Identify Features or openTable Open Attribute Table or actionRun 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 você está chamando uma ação que usa o ``% ``% notação, clique com o botão direito sobre o valor do campo na: guilabel: `` Identificar resultados de diálogo ou o: guilabel: ‘Tabela de atributos` diálogo que você deseja passar para a aplicação ou script.

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 nix or perhaps osx). 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"

Depois de selecionar algumas localidades e executar a ação em cada um, a abertura do arquivo de saída irái mostrar algo como isto:

Acacia mearnsii -34.0800000000 150.0800000000
Acacia mearnsii -34.9000000000 150.1200000000
Acacia mearnsii -35.2200000000 149.9300000000
Acacia mearnsii -32.2700000000 150.4100000000

Como um exercício, criamos uma ação que faz uma pesquisa no Google sobre o a camada lagos. Primeiro, precisamos determinar o URL necessário para realizar uma pesquisa sobre a palavra-chave. Isso póde ser realizado facilmente indo ao Google e realizando uma pesquisa simples, em seguida, pegar a URL na barra de endereços do seu navegador. A partir deste pequeno esforço, vemos que o formato é: http://google.com/search?q=qgis , onde QGIS é o termo de pesquisa. Armado com esta informação, podemos prosseguir:

  1. Verifique se a camada lagos está carregada.

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

  3. Clique em :guilabel: menu ‘Ações’.

  4. Digite um nome para a ação, por exemplo `` Google Search ``.

  5. Para a ação, precisamos fornecer o nome do programa externo a ser executado. Neste caso, podemos usar o Firefox. Se o programa não estiver em seu caminho, você precisará fornecer o caminho completo.

  6. Seguindo o nome da aplicação externa, adicione a URL usada para fazer uma pesquisa no Google, mas não inclua o termo de busca: `` http://google.com/search?q=``

  7. O texto no campo de ação será mostrado como este: `` firefox http://google.com/search?q =``

  8. Clique na caixa oculta que contém os nomes dos campos para camada ” lagos”. Ele está localizado logo ao lado esquerdo do botão [Inserir Campo] .

  9. A partir da caixa drop-down, selecione ‘NOMES’ e clique ** [Inserir campo]. **

  10. Seu texto ação agora se parecerá como este:

    firefox http://google.com/search?q=%NAMES

  11. Para finalizar a ação, clique no botão [Adicionar à lista de ações].

Isso completa a ação, e ele está pronto para usar. O texto final da ação deve ser semelhante a este:

firefox http://google.com/search?q=%NAMES

Agora podemos utilizar a ação. Feche a: aba de diálogo: ‘Propriedades da camada ` e aplique um zoom em uma área de interesse. Certifique-se que a camada lagos está ativa e identifique um lago. Na caixa o resultado que você poderá visualizar que a nossa ação está visível:

Figure Actions 2:


Select feature and choose action

Quando clicamos sobre a ação, ela faz o Firefox e navegar para o URL http://www.google.com/search?q=Tustumena. Também é possível adicionar outros campos de atributo para essa açao. Para isso basta um + ao final do texto de ação, selecionar outro campo e clicar em [Inserir Campo]. Nesse exemplo não temos outro campo disponível para efetuarmos a busca.

Você pode definir várias ações para uma camada, e cada um vai aparecer no diálogo Identificar resultados.

You can also invoke actions from the attribute table by selecting a row and right-clicking, then choosing the action from the pop-up menu.

Há todos os tipos de usos para as ações. Por exemplo, se você tem uma camada de pontos que contém as localizações de imagens ou fotos, juntamente com um nome de arquivo, você pode criar uma ação para lançar um visualizador para exibir a imagem. Você também pode usar ações para lançar relatórios baseados na web para um campo de atributo ou combinação de campos, especificando-as da mesma forma que fizemos no nosso exemplo de busca Google.

Nós também podemos fazer exemplos mais complexos, por exemplo, usando ações Python.

Normalmente, quando nós criamos uma ação para abrir um arquivo com uma aplicação externa, podemos usar caminhos absolutos, ou, eventualmente, caminhos relativos. No segundo caso, o caminho é relativo ao local do arquivo executável do programa externo. Mas o que dizer se precisamos usar caminhos relativos, em relação à camada selecionada (um baseado em arquivo, como um shapefile ou SpatiaLite)? O código a seguir irá fazer o truque:

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

Nós apenas temos que lembrar que a ação é um do tipo variáveis Python e o comando e imagerelpath ​​devem ser alteradas para atender as necessidades.

Mas o que dizer se o caminho relativo deve ser relativo ao arquivo de projeto (salvo)? O código da ação Python seria:

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

Outro exemplo de ação Python é a que nos permite adicionar novas camadas ao projeto. Por exemplo, os exemplos a seguir irão adicionar ao projeto, respectivamente, um vetor e raster. Os nomes dos arquivos a serem adicionados ao projeto e os nomes a serem indicados para as camadas são conduzidos de dados (nome do arquivo e nome da camada são nomes da tabela de atributos do vetor, onde a ação foi criada coluna):

qgis.utils.iface.addVectorLayer('/yourpath/[% "filename" %].shp',
  '[% "layername" %]', 'ogr')

Para adicionar um raster (uma imagem TIF neste exemplo), ele se torna:

qgis.utils.iface.addRasterLayer('/yourpath/[% "filename" %].tif',
  '[% "layername" %]')

Menu Visualização

mapTips This menu is specifically created for Map Tips. It includes a nice feature: Map Tip display text in HTML. While you can still choose a radioButtonOff Field to be displayed when hovering over a feature on the map, it is also possible to insert HTML code that creates a complex display when hovering over a feature. To activate Map Tips, select the menu option View ‣ Map Tips.

Figure Display 1 and 2 show an example of HTML code and how it behaves in map canvas.

Figure Display 1:


HTML code for map tip

Figure Display 2:


Map tip made with HTML code

Menu Renderizador

QGIS offers 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 checkbox Simplify geometry option. There is also a global setting that enables generalisation by default for newly added layers (see section Opções).

Figure Rendering 1:


Layer Geometry Simplification dialog


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.

While rendering extremely detailed layers (e.g. polygon layers with a huge number of nodes), this can cause composer exports in PDF/SVG format to be huge as all nodes are included in the exported file. This can also make the resultant file very slow to work with/open in other programs.

Checking checkbox Force layer to render as raster forces these layers to be rasterised so that the exported files won’t have to include all the nodes contained in these layers and the rendering is therefore sped up.

You can also do this by forcing the composer to export as a raster, but that is an all-or-nothing solution, given that the rasterisation is applied to all layers.

Menu Metadados

metadata The Metadata menu consists of Description, Attribution, MetadataURL, LegendUrl 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 information on the layer extent and the Layer Spatial Reference System, which is information about the CRS of the layer. This can provide a quick way to get useful 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.

In the LegendUrl section, you can provide the url of a legend image in the url field. You can use the Format drop-down option to apply the appropriate format of the image. Currently png, jpg and jpeg image formats are supported.

Figure Metadata 1:


Metadata menu in vector layers properties dialog

Save and Share Layer Properties

Managing Custom Styles

When a layer is added to map canvas, QGIS uses by default a random symbol/color to render its features. You can however set a default symbol in Project ‣ Properties ‣ Default styles that will be applied to each newly added layer according to its geometry type.

But, most of the time, you’d prefer to have a custom and more complex style that can be applied automatically or manually (with less efforts) to the layers. You can achieve this goal using the Style combobox at the bottom of the Layer Properties dialog. This combobox provides you with functions to create, load and manage styles.

A style stores any information set in the layer properties dialog to render or interact with the features (including symbology, labeling, action, diagram... settings).

Figure Vector Properties 10:


Style combobox options

By default, the style applied to a loaded layer is named default. Once you have got the ideal and appropriate rendering for your layer, you can save it by clicking the selectString Style combobox and choose:

  • Rename Current: The active style gets renamed and updated with the current options
  • Add: A new style is created using the current options.

At the bottom of the Style drop-down list, you see the styles set for the layer and the active one is checked. Once you have more than one style defined for a layer, a Remove Current option can help you delete those you no longer want.

Note that each time you validate the layer properties dialog, the active style is updated with the changes you’ve done.

You can create as many styles as you wish for a layer but only one can be active at a time. Combined to layer visibility preset, this offers a quick and powerful way to manage complex projects with few layers (no need to duplicate any layer in the map legend).


Manage styles from layer context menu

Right-click on the layer in Layers Panel to add, rename or remove layer style. You can also edit feature symbols.

Storing Style in a File or a Database

While these styles are saved inside the project and can be copied and pasted from layer to layer in the project, it’s also possible to save them outside the project so that they can be loaded in another project. Clicking the selectString Style ‣ Save Style saves 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.

If the datasource of the layer is a database (PostGIS or Spatialite for example), you can also save your layer style inside a table of the database. Just click on Save Style combobox and choose Save in database item then fill in the dialog to define a style name, add a description, an ui file if applicable and check if the style is the default style. You can add several style in the database. However each table can have only one default style.

When loading a layer in QGIS, if a default style already exists for this layer, QGIS will load the layer and its style. After you modified the layer style, you can Save as Default, creating a new style that becomes the default one or Restore Default style if you’re not satisfied.

Figure Vector Properties 2:


Save Style in database Dialog


Quickly share a layer style within the project

You can also share layer style within a project without importing a file or database style: right-click on the layer in the Layers Panel and, from the Styles combobox , copy the style of a layer and paste it to a group or a selection of layers: the style is applied to all the layers that are of the same type (vector vs raster) as the original layer and, in case of vector, have the same geometry type (point, line or polygon).