Expresiones

Basada en datos de capa y funciones predefinidas o definidas por el usuario, Expressions ofrece una forma poderosa de manipular el valor del atributo, la geometría y las variables para cambiar dinámicamente el estilo de la geometría, el contenido o la posición de la etiqueta, el valor del diagrama, la altura de un elemento de diseño, seleccionar algunas entidades, cree un campo virtual …

El constructor de cadena de Expresión

El diálogo principal para construir expresiones, el :guilabel: Expression string builder está disponible desde muchas partes en QGIS y, en particular, se puede acceder mediante:

El cuadro de diálogo del generador de expresiones ofrece acceso a:

  • Expression tab que, gracias a una lista de funciones predefinidas, ayuda a escribir y verificar la expresión a usar;

  • Function Editor tab lo que ayuda a ampliar la lista de funciones mediante la creación de funciones personalizadas.

Algunos casos de uso de expresiones:

  • Desde la Calculadora de campos, calcule un campo «pop_density» utilizando los campos existentes «total_pop» y «area_km2»

    "total_pop" / "area_km2"
    
  • Actualice el campo «density_level» con categorías de acuerdo con los valores «pop_density»

    CASE WHEN "pop_density" < 50 THEN 'Low population density'
         WHEN "pop_density" >= 50 and "pop_density" < 150 THEN 'Medium population density'
         WHEN "pop_density" >= 150 THEN 'High population density'
    END
    
  • Apply a categorized style to all the features according to whether their average house price is smaller or higher than 10000€ per square metre:

    "price_m2" > 10000
    
  • Using the «Select By Expression…» tool, select all the features representing areas of “High population density” and whose average house price is higher than 10000€ per square metre:

    "density_level" = 'High population density' and "price_m2" > 10000
    

    Likewise, the previous expression could also be used to define which features should be labeled or shown in the map.

Using expressions offers you a lot of possibilities.

Truco

Use named parameters to improve the expression reading

Some functions require many parameters to be set. The expression engine supports the use of named parameters. This means that instead of writing the cryptic expression clamp( 1, 2, 9), you can use clamp( min:=1, value:=2, max:=9). This also allows arguments to be switched, e.g. clamp( value:=2, max:=9, min:=1). Using named parameters helps clarify what the arguments for an expression function refer to, which is helpful when you are trying to interpret an expression at a later date!

Lista de funciones

The Expression tab provides the main interface to write expressions using functions, layer’s fields and values. It contains following widgets:

  • An expression editor area to type or paste expressions. Autocompletion is available to speed expression writing:

    • Corresponding variables, function names and field names to the input text are shown below: use the Up and Down arrows to browse the items and press Tab to insert in the expression or simply click on the wished item.

    • Function parameters are shown while filling them.

    QGIS also checks the expression rightness and highlights all the errors using:

    • Underline: for unknown functions, wrong or invalid arguments;

    • Marker: for every other error (eg, missing parenthesis, unexpected character) at a single location.

    Truco

    Document your expression with comments

    When using complex expression, it is good practice to add text either as a multiline comment or inline comments to help you remember.

    /*
    Labels each region with its highest (in altitude) airport(s)
    and altitude, eg 'AMBLER : 264m' for the 'Northwest Artic' region
    */
    with_variable(
      'airport_alti', -- stores the highest altitude of the region
      aggregate(
        'airports',
        'max',
        "ELEV", -- the field containing the altitude
        -- and limit the airports to the region they are within
        filter := within( $geometry, geometry( @parent ) )
      ),
        aggregate( -- finds airports at the same altitude in the region
          'airports',
          'concatenate',
          "NAME",
          filter := within( $geometry, geometry( @parent ) )
            and "ELEV" = @airport_alti
        )
        || ' : ' || @airport_alti || 'm'
        -- using || allows regions without airports to be skipped
    )
    
  • Under the expression editor, an Output preview displays the result of the expression evaluated on the first feature of the layer. In case of error, it indicates it and you can access details with the provided hyperlink.

  • A function selector displays the list of functions, variables, fields… organized in groups. A search box is available to filter the list and quickly find a particular function or field. Double-clicking an item adds it to the expression editor.

  • A help panel displays help for each selected item in the function selector.

    Truco

    Press Ctrl+Click when hovering a function name in an expression to automatically display its help in the dialog.

    A field’s values widget shown when a field is selected in the function selector helps to fetch features attributes. Double-clicking a value adds it to the expression editor.

    Truco

    The right panel, showing functions help or field values, can be collapsed (invisible) in the dialog. Press the Show Values or Show Help button to get it back.

../../../_images/function_list.png

The Expression tab

Aggregates Functions

This group contains functions which aggregate values over layers and fields.

Función

Descripción

agregar

Returns an aggregate value calculated using features from another layer

array_agg

Returns an array of aggregated values from a field or expression

collect

Returns the multipart geometry of aggregated geometries from an expression

concatenar

Returns all aggregated strings from a field or expression joined by a delimiter

concatenate_unique

Returns all unique aggregated strings from a field or expression joined by a delimiter

Número

Returns the count of matching features

count_distinct

Returns the count of distinct values

count_missing

Returns the count of missing (null) values

iqr

Returns the calculated inter quartile range from a field or expression

mayoría

Returns the aggregate majority of values (most commonly occurring value) from a field or expression

max_length

Returns the maximum length of strings from a field or expression

máximo

Returns the aggregate maximum value from a field or expression

media

Returns the aggregate mean value from a field or expression

mediana

Returns the aggregate median value from a field or expression

min_length

Returns the minimum length of strings from a field or expression

mínimo

Returns the aggregate minimum value from a field or expression

minoría

Returns the aggregate minority of values (least commonly occurring value) from a field or expression

q1

Returns the calculated first quartile from a field or expression

q3

Devuelve el tercer cuartil calculado a partir de un campo o expresión

intervalo

Returns the aggregate range of values (maximum - minimum) from a field or expression

relation_aggregate

Returns an aggregate value calculated using all matching child features from a layer relation

stdev

Returns the aggregate standard deviation value from a field or expression

sum

Returns the aggregate summed value from a field or expression

Ejemplos:

  • Return the maximum of the «passengers» field from features in the layer grouped by «station_class» field:

    maximum("passengers", group_by:="station_class")
    
  • Calculate the total number of passengers for the stations inside the current atlas feature:

    aggregate('rail_stations','sum',"passengers",
      intersects(@atlas_geometry, $geometry))
    
  • Return the mean of the «field_from_related_table» field for all matching child features using the “my_relation” relation from the layer:

    relation_aggregate('my_relation', 'mean', "field_from_related_table")
    

    o:

    relation_aggregate(relation:='my_relation', aggregate := 'mean',
      expression := "field_from_related_table")
    

Array Functions

This group contains functions to create and manipulate arrays (also known as list data structures). The order of values within the array matters, unlike the “map” data structure, where the order of key-value pairs is irrelevant and values are identified by their keys.

Función

Descripción

array

Returns an array containing all the values passed as parameter

array_all

Returns true if an array contains all the values of a given array

array_append

Returns an array with the given value added at the end

array_cat

Returns an array containing all the given arrays concatenated

array_contains

Returns true if an array contains the given value

array_distinct

Returns an array containing distinct values of the given array

array_filter

Returns an array with only the items for which an expression evaluates to true

array_find

Returns the index (0 for the first one) of a value within an array. Returns -1 if the value is not found.

array_first

Returns the first value of an array

array_foreach

Returns an array with the given expression evaluated on each item

array_get

Returns the Nth value (0 for the first one) of an array

array_insert

Returns an array with the given value added at the given position

array_intersect

Returns true if any element of array_1 exists in array_2

array_last

Returns the last element of an array

array_length

Returns the number of elements of an array

array_prepend

Returns an array with the given value added at the beginning

array_remove_all

Returns an array with all the entries of the given value removed

array_remove_at

Returns an array with the given index removed

array_reverse

Returns the given array with array values in reversed order

array_slice

Returns the values of the array from the start_pos argument up to and including the end_pos argument

array_sort

Returns the provided array with its elements sorted

array_to_string

Concatenates array elements into a string separated by a delimiter and using optional string for empty values

generate_series

Creates an array containing a sequence of numbers

regexp_matches

Returns an array of all strings captured by capturing groups, in the order the groups themselves appear in the supplied regular expression against a string

string_to_array

Splits string into an array using supplied delimiter and optional string for empty values

Funciones de Color

This group contains functions for manipulating colors.

Función

Descripción

color_cmyk

Devuelve una representación en forma de cadena de un color en base a sus componentes cian, magenta, amarillo y negro

color_cmyka

Returns a string representation of a color based on its cyan, magenta, yellow, black and alpha (transparency) components

color_grayscale_average

Applies a grayscale filter and returns a string representation from a provided color

color_hsl

Returns a string representation of a color based on its hue, saturation, and lightness attributes

color_hsla

Devuelve una representación en forma de cadena de un color en base a sus atributos de matiz, saturación, luminosidad y canal alfa (transparencia).

color_hsv

Returns a string representation of a color based on its hue, saturation, and value attributes

color_hsva

Devuelve una representación en forma de cadena de un color en base a sus atributos de matiz, saturación, valor y canal alfa (transparencia)

color_mix_rgb

Returns a string representing a color mixing the red, green, blue, and alpha values of two provided colors based on a given ratio

color_part

Devuelve un componente específico de la cadena de un color, por ejemplo el componente rojo o el alfa

color_rgb

Returns a string representation of a color based on its red, green, and blue components

color_rgba

Returns a string representation of a color based on its red, green, blue, and alpha (transparency) components

create_ramp

Returns a gradient ramp from a map of color strings and steps

más oscuro

Devuelve una cadena de color más oscura (o más clara)

más claro

Devuelve una cadena de color más clara (o más oscura)

project_color

Devuelve un color del esquema de color del proyecto

ramp_color

Devuelve una cadena que representa un color de una rampa de color

set_color_part

Sets a specific color component for a color string, eg the red component or alpha component

Conditional Functions

Este grupo contiene funciones para menejar comprobaciones condicionales en expresiones.

Función

Descripción

CASE WHEN … THEN … END

Evalúa una expresión y devuelve un resultado si es verdadera. Puede probar múltiples condiciones

CASE WHEN … THEN … ELSE … END

Evalúa una expresión y devuelva un resultado diferente sea verdadero o falso. Puede probar múltiples condiciones

coalesce

Devuelve el primer valor no-NULO de la lista de expresión

si

Prueba una condición y devuelve un resultado diferente dependiendo de la comprobación condicional

nullif(value1, value2)

Returns a null value if value1 equals value2 otherwise it returns value1. This can be used to conditionally substitute values with NULL.

try

Tries an expression and returns its value if error-free, an alternative value (if provided) or Null if an error occurs

Algún ejemplo:

  • Send back a value if the first condition is true, else another value:

    CASE WHEN "software" LIKE '%QGIS%' THEN 'QGIS' ELSE 'Other' END
    

Funciones de conversión

This group contains functions to convert one data type to another (e.g., string to integer, integer to string).

Función

Descripción

to_date

Convierte una cadena de texto en un objeto fecha

to_datetime

Converts a string into a datetime object

to_dm

Converts a coordinate to degree, minute

to_dms

Converts coordinate to degree, minute, second

to_int

Convierte una cadena de texto a número entero

to_interval

Converts a string to an interval type (can be used to take days, hours, months, etc. of a date)

to_real

Convierte una cadena de texto en número real

to_string

Convierte un número en cadena.

to_time

Converts a string into a time object

Funciones personalizadas

This group contains functions created by the user. See Editor de Funciones for more details.

Funciones de Fecha y Hora

Este grupo contiene funciones para manipular datos de fecha y hora.

Función

Descripción

edad

Returns as an interval the difference between two dates or datetimes

día

Extracts the day from a date or datetime, or the number of days from an interval

day_of_week

Returns a number corresponding to the day of the week for a specified date or datetime

epoch

Returns the interval in milliseconds between the unix epoch and a given date value

hora

Extracts the hour from a datetime or time, or the number of hours from an interval

minuto

Extracts the minute from a datetime or time, or the number of minutes from an interval

mes

Extracts the month part from a date or datetime, or the number of months from an interval

now

Returns current date and time

segundo

Extracts the second from a datetime or time, or the number of seconds from an interval

semana

Extrae el número de la semana de una fecha o el número de semanas de un intervalo.

year

Extracts the year part from a date or datetime, or the number of years from an interval

This group also shares several functions with the Funciones de conversión ( to_date, to_time, to_datetime, to_interval) and Funciones de cadena (format_date) groups.

Algún ejemplo:

  • Get today’s month and year in the «month_number/year» format:

    format_date(now(),'MM/yyyy')
    -- Returns '03/2017'
    

Besides these functions, subtracting dates, datetimes or times using the - (minus) operator will return an interval.

Adding or subtracting an interval to dates, datetimes or times, using the + (plus) and - (minus) operators, will return a datetime.

  • Get the number of days until QGIS 3.0 release:

    to_date('2017-09-29') - to_date(now())
    -- Returns <interval: 203 days>
    
  • The same with time:

    to_datetime('2017-09-29 12:00:00') - to_datetime(now())
    -- Returns <interval: 202.49 days>
    
  • Get the datetime of 100 days from now:

    now() + to_interval('100 days')
    -- Returns <datetime: 2017-06-18 01:00:00>
    

Nota

Storing date and datetime and intervals on fields

The ability to store date, time and datetime values directly on fields may depend on the data source’s provider (e.g., Shapefile accepts date format, but not datetime or time format). The following are some suggestions to overcome this limitation:

  • date, Datetime and time can be stored in text type fields after using the to_format() function.

  • Intervals can be stored in integer or decimal type fields after using one of the date extraction functions (e.g., day() to get the interval expressed in days)

Campos y Valores

Contains a list of fields from the layer.

Double-click a field name to have it added to your expression. You can also type the field name (preferably inside double quotes) or its alias.

To retrieve fields values to use in an expression, select the appropriate field and, in the shown widget, choose between 10 Samples and All Unique. Requested values are then displayed and you can use the Search box at the top of the list to filter the result. Sample values can also be accessed via right-clicking on a field.

To add a value to the expression you are writing, double-click on it in the list. If the value is of a string type, it should be simple quoted, otherwise no quote is needed.

Files and Paths Functions

This group contains functions which manipulate file and path names.

Función

Descripción

base_file_name

Returns the base name of the file without the directory or file suffix.

file_exists

Returns true if a file path exists.

file_name

Returns the name of a file (including the file extension), excluding the directory.

file_path

Returns the directory component of a file path, without the file name

file_size

Returns the size (in bytes) of a file.

file_suffix

Returns the file extension from a file path.

is_directory

Returns true if a path corresponds to a directory.

is_file

Returns true if a path corresponds to a file.

Funciones Concordancia aproximada

This group contains functions for fuzzy comparisons between values.

Función

Descripción

hamming_distance

Returns the number of characters at corresponding positions within the input strings where the characters are different

levensheim

Returns the minimum number of character edits (insertions, deletions or substitutions) required to change one string to another. Measure the similarity between two strings

longest_common_substring

Returns the longest common substring between two strings

soundex

Returns the Soundex representation of a string

Funciones Generales

This group contains general assorted functions.

Función

Descripción

env

Gets an environment variable and returns its content as a string. If the variable is not found, NULL will be returned.

eval

Evaluates an expression which is passed in a string. Useful to expand dynamic parameters passed as context variables or fields.

is_layer_visible

Returns true if a specified layer is visible

layer_property

Returns a property of a layer or a value of its metadata. It can be layer name, crs, geometry type, feature count…

var

Returns the value stored within a specified variable. See variable functions below

with_variable

Creates and sets a variable for any expression code that will be provided as a third argument. Useful to avoid repetition in expressions where the same value needs to be used more than once.

Funciones de Geometría

This group contains functions that operate on geometry objects (e.g., length, area).

Función

Descripción

$area

Returns the area size of the current feature

$geometry

Returns the geometry of the current feature (can be used for processing with other functions)

$length

Returns the length of the current line feature

$perimeter

Returns the perimeter of the current polygon feature

$x

Returns the X coordinate of the current feature

$x_at(n)

Returns the X coordinate of the nth node of the current feature’s geometry

$y

Returns the Y coordinate of the current feature

$y_at(n)

Returns the Y coordinate of the nth node of the current feature’s geometry

angle_at_vertex

Returns the bisector angle (average angle) to the geometry for a specified vertex on a linestring geometry. Angles are in degrees clockwise from north

area

Devuelve el perímetro de un objeto de geometría poligonal. Los cálculos están en el Sistema de Referencia Espacial de esta geometría

azimut

Returns the north-based azimuth as the angle in radians measured clockwise from the vertical on point_a to point_b

contorno

Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the geometry - see also Contorno).

límites

Returns a geometry which represents the bounding box of an input geometry. Calculations are in the Spatial Reference System of this geometry (see also Recuadros delimitadores)

bounds_height

Returns the height of the bounding box of a geometry. Calculations are in the Spatial Reference System of this geometry

bounds_width

Devuelve la anchura del recuadro delimitador de una geometría. Los cálculos están en el Sistema de Referencia Espacial de esta geometría

buffer

Returns a geometry that represents all points whose distance from this geometry is less than or equal to distance. Calculations are in the Spatial Reference System of this geometry (see also Buffer)

buffer_by_m

Creates a buffer along a line geometry where the buffer diameter varies according to the M values at the line vertices (see also Variable ancho del buffer (por valor M)Ancura de buffer variable (por valor de M))

centroid

Returns the geometric center of a geometry (see also Centroides)

closest_point

Returns the point on a geometry that is closest to a second geometry

collect_geometries

Collects a set of geometries into a multi-part geometry object (see also Coleccionar geometrías)

combinar

Devuelve la combinación de dos geometrías

contains(a,b)

Returns 1 (true) if and only if no points of b lie in the exterior of a, and at least one point of the interior of b lies in the interior of a

convex_hull

Returns the convex hull of a geometry (this represents the minimum convex geometry that encloses all geometries within the set) (see also Casco convexo)

cruza

Returns 1 (true) if the supplied geometries have some, but not all, interior points in common

difference(a,b)

Returns a geometry that represents that part of geometry a that does not intersect with geometry b (see also Difference)

inconexo

Returns 1 (true) if the geometries do not share any space together

distance

Returns the minimum distance (based on Spatial Reference System) between two geometries in projected units

distance_to_vertex

Returns the distance along the geometry to a specified vertex

end_point

Returns the last node from a geometry (see also Extráe vértices específicos)

extend

Extends the start and end of a linestring geometry by a specified amount (see also Extender líneas)

exterior_ring

Returns a line string representing the exterior ring of a polygon geometry, or null if the geometry is not a polygon

extrude(geom,x,y)

Returns an extruded version of the input (Multi-) Curve or (Multi-)Linestring geometry with an extension specified by X and Y

flip_coordinates

Returns a copy of the geometry with the X and Y coordinates swapped (see also Intercmbiar coordenadas X e Y)

force_rhr

Forces a geometry to respect the Right-Hand-Rule (see also Fuerza la regla de la mano derecha)

geom_from_gml

Returns a geometry created from a GML representation of geometry

geom_from_wkt

Returns a geometry created from a well-known text (WKT) representation

geom_to_wkt

Returns the well-known text (WKT) representation of the geometry without SRID metadata

geometry

Devuelve la geometría de un objeto

geometry_n

Returns the nth geometry from a geometry collection, or null if the input geometry is not a collection

hausdorff_distance

Returns basically a measure of how similar or dissimilar two geometries are, with a lower distance indicating more similar geometries

inclination

Returns the inclination measured from the zenith (0) to the nadir (180) on point_a to point_b

interior_ring_n

Returns the geometry of the nth interior ring from a polygon geometry, or null if the geometry is not a polygon

intersección

Returns a geometry that represents the shared portion of two geometries (see also Intersection)

intersecta

Tests whether a geometry intersects another. Returns 1 (true) if the geometries spatially intersect (share any portion of space) and 0 if they don’t

intersects_bbox

Tests whether a geometry’s bounding box overlaps another geometry’s bounding box. Returns 1 (true) if the geometries spatially intersect (share any portion of space) their bounding box, or 0 if they don’t

is_closed

Returns true if a line string is closed (start and end points are coincident), false if a line string is not closed, or null if the geometry is not a line string

longitud

Returns length of a line geometry feature (or length of a string)

line_interpolate_angle

Returns the angle parallel to the geometry at a specified distance along a linestring geometry. Angles are in degrees clockwise from north.

line_interpolate_point

Returns the point interpolated by a specified distance along a linestring geometry. (see also Interpolar puntos en línea)

line_locate_point

Returns the distance along a linestring corresponding to the closest position the linestring comes to a specified point geometry.

line_merge

Returns a (Multi-)LineString geometry, where any connected LineStrings from the input geometry have been merged into a single linestring.

line_substring

Returns the portion of a line or curve geometry falling betweeen specified start and end distances (measured from the beginning of the line) (see also Subcadena de línea)

m

Returns the M value of a point geometry

make_circle

Creates a circular geometry based on center point and radius

make_ellipse

Creates an elliptical geometry based on center point, axes and azimuth

make_line

Creates a line geometry from a series or an array of point geometries

make_point(x,y,z,m)

Returns a point geometry from X and Y (and optional Z or M) values

make_point_m(x,y,m)

Returns a point geometry from X and Y coordinates and M values

make_polygon

Crea una geometría de polígono a partir de un anillo exterior y series opcionales de geometrías interiores de anillo

make_rectangle_3points

Creates a rectangle from 3 points

make_regular_polygon

Creates a regular polygon

make_square

Creates a square from a diagonal

make_triangle

Creates a triangle polygon

minimal_circle

Returns the minimal enclosing circle of an input geometry (see also Cícrculos mínimos cercantes)

nodes_to_points

Returns a multipoint geometry consisting of every node in the input geometry (see also Extraer vértices)

num_geometries

Devuelve el número de geometrías en una colección de geometrías o nulo si la geometría de entrada no es una colección

num_interior_rings

Devuelve el número de anillos interiores de un polígono o una colección de geometrías o nulo si la geometría de entrada no es un polígono o una colección

num_points

Devuelve el número de vértices de una geometría.

num_rings

Devuelve el número de anillos (incluidos los anillos exteriores) de un polígono o una colección de geometrías o nulo si la geometría de entrada no es un polígono o una colección

offset_curve

Returns a geometry formed by offsetting a linestring geometry to the side. Distances are in the Spatial Reference System of this geometry. (see also Compensado de líneas)

order_parts

Ordena las partes de una MultiGeometría por los criterios dados

oriented_bbox

Returns a geometry representing the minimal oriented bounding box of an input geometry (see also Cuador delimitador mínimo orientado)

solapa

Comprueba si una geometría solapa con otra. Devuelve 1(verdadero) si las geometrías comparten espacio, son de la misma dimensión, pero no están contenidas en la otra.

perímetro

Devuelve el perímetro de un objeto de geometría poligonal. Los cálculos están en el Sistema de Referencia Espacial de esta geometría.

point_n

Returns a specific node from a geometry (see also Extráe vértices específicos)

point_on_surface

Returns a point guaranteed to lie on the surface of a geometry (see also Punto en la superficie)

pole_of_inaccessibility

Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface (see also Polo de inaccesibilidad)

proyecto

Returns a point projected from a start point using a distance, a bearing (azimuth) and an elevation in radians (see also Proyección de puntos (Cartesiano))

relate

Prueba o devuelve la representación del Modelo de Intersección 9 Extendido Dimensional (DE-9IM) de la relación entre dos geometrías.

invertir

Reverses the direction of a line string by reversing the order of its vertices (see also Línea de dirección reversible)

segments_to_lines

Returns a multi line geometry consisting of a line for every segment in the input geometry (see also Explotar lineas)

shortest_line

Returns the shortest line joining two geometries. The resultant line will start at geometry 1 and end at geometry 2

simplify

Simplifies a geometry by removing nodes using a distance based threshold (see also Simplificar)

simplify_vw

Simplifies a geometry by removing nodes using an area based threshold (see also Simplificar)

single_sided_buffer

Returns a geometry formed by buffering out just one side of a linestring geometry. Distances are in the Spatial Reference System of this geometry (see also Buffer a un solo lado)

smooth

Smooths a geometry by adding extra nodes which round off corners in the geometry (see also Suavizar)

start_point

Returns the first node from a geometry (see also Extráe vértices específicos)

sym_difference

Returns a geometry that represents the portions of two geometries that do not intersect (see also Symmetrical difference)

tapered_buffer

Creates a buffer along a line geometry where the buffer diameter varies evenly over the length of the line (see also Tapered buffers)

toca

Tests whether a geometry touches another. Returns 1 (true) if the geometries have at least one point in common, but their interiors do not intersect

Transformar

Returns the geometry transformed from the source CRS to the destination CRS (see also Reproject layer)

Convertir

Returns a translated version of a geometry. Calculations are in the Spatial Reference System of the geometry (see also Traslado)

unión

Devuelve una geometría que representa el conjunto unión de los puntos de las geometrías.

wedge_buffer

Returns a wedge shaped buffer originating from a point geometry given an angle and radii (see also Crear buffer de cuñas)

entre(a,b)

Tests whether a geometry is within another. Returns 1 (true) if geometry a is completely inside geometry b

x

Returns the X coordinate of a point geometry, or the X coordinate of the centroid for a non-point geometry

x_max

Returns the maximum X coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

x_min

Returns the minimum X coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

y

Returns the Y coordinate of a point geometry, or the Y coordinate of the centroid for a non-point geometry

y_max

Returns the maximum Y coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

y_min

Returns the minimum Y coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry

z

Returns the Z coordinate of a point geometry

Algún ejemplo:

  • Return the X coordinate of the current feature’s centroid:

    x( $geometry )
    
  • Send back a value according to feature’s area:

    CASE WHEN $area > 10 000 THEN 'Larger' ELSE 'Smaller' END
    
  • You can manipulate the current geometry using the variable $geometry to create a buffer or get a point on the geometry’s surface:

    buffer( $geometry, 10 )
    point_on_surface( $geometry )
    
  • Given a point feature, generate a closed line (using make_line) around the point’s geometry:

    make_line(
      -- using an array of points placed around the original
      array_foreach(
        -- list of angles for placing the projected points (every 90°)
        array:=generate_series( 0, 360, 90 ),
        -- translate the point 20 units in the given direction (angle)
        expression:=project( $geometry, distance:=20, azimuth:=radians( @element ) )
      )
    )
    

Layout Functions

This group contains functions to manipulate print layout items properties.

Función

Descripción

item_variables

Returns a map of variables from a layout item inside this print layout

An example:

  • Get the scale of the “Map 0” in the current print layout:

    map_get( item_variables('Map 0'), 'map_scale')
    

Map Layers

This group contains a list of the available layers in the current project. This offers a convenient way to write expressions referring to multiple layers, such as when performing aggregates, attribute or spatial queries.

It also provides some convenient functions to manipulate layers.

Función

Descripción

decode_uri

Takes a layer and decodes the uri of the underlying data provider. Available information depends on the data provider type.

Maps Functions

This group contains functions to create or manipulate keys and values of map data structures (also known as dictionary objects, key-value pairs, or associative arrays). Unlike the list data structure where values order matters, the order of the key-value pairs in the map object is not relevant and values are identified by their keys.

Función

Descripción

from_json

Loads a json-formatted string

hstore_to_map

Creates a map from a hstore-formatted string

json_to_map

Creates a map from a json-formatted string

map

Returns a map containing all the keys and values passed as pair of parameters

map_akeys

Returns all the keys of a map as an array

map_avals

Returns all the values of a map as an array

map_concat

Returns a map containing all the entries of the given maps. If two maps contain the same key, the value of the second map is taken.

map_delete

Returns a map with the given key and its corresponding value deleted

map_exist

Returns true if the given key exists in the map

map_get

Returns the value of a map, given it’s key

map_insert

Returns a map with an added key/value

map_to_hstore

Merges map elements into a hstore-formatted string

map_to_json

Merges map elements into a json-formatted string

to_json

Creates a json-formatted string from a map, an array or other value

Funciones Matemáticas

Este grupo contiene funciones matemáticas,por ejemplo raíz cuadrada, seno y coseno

Función

Descripción

abs

Devuelve el valor absoluto de un número

arcos

Devuelve la inversa del coseno de un valor en radianes

arcsen

Devuelve la inversa del seno de un valor en radianes

atan

Returns the inverse tangent of a value in radians

atan2(y,x)

Returns the inverse tangent of Y/X by using the signs of the two arguments to determine the quadrant of the result

azimuth(a,b)

Returns the north-based azimuth as the angle in radians measured clockwise from the vertical on point a to point b

ceil

Rounds a number upwards

clamp

Restricts an input value to a specified range

cos

Returns the cosine of an angle in radians

grados

Convierte de radianes a grados

exp

Devuelve la exponencial de un valor

floor

Rounds a number downwards

inclination

Returns the inclination measured from the zenith (0) to the nadir (180) on point_a to point_b.

ln

Returns the natural logarithm of the passed expression

log

Returns the value of the logarithm of the passed value and base

log10

Returns the value of the base 10 logarithm of the passed expression

máx

Returns the largest not null value in a set of values

mín

Returns the smallest not null value in a set of values

pi

Returns the value of pi for calculations

radianes

Convierte de grados a radianes

rand

Returns the random integer within the range specified by the minimum and maximum argument (inclusive)

randf

Returns the random float within the range specified by the minimum and maximum argument (inclusive)

round

Rounds to number of decimal places

scale_exp

Transforma un valor dado de un dominio de entrada a un rango de salida usando una curva exponencial

scale_linear

Transforma un valor dado de un dominio de entrada a un rango de salida usando interpolación lineal

sen

Returns the sine of an angle in radians

raíz cuadrada

Returns the square root of a value

tan

Returns the tangent of an angle in radians

Operadores

This group contains operators (e.g., +, -, *). Note that for most of the mathematical functions below, if one of the inputs is NULL then the result is NULL.

Función

Descripción

a + b

Addition of two values (a plus b)

a - b

Subtraction of two values (a minus b).

a * b

Multiplication of two values (a multiplied by b)

a / b

División de dos valores (a dividido entre b)

a % b

Remainder of division of a by b (eg, 7 % 2 = 1, or 2 fits into 7 three times with remainder 1)

a ^ b

Power of two values (for example, 2^2=4 or 2^3=8)

a < b

Compares two values and evaluates to 1 if the left value is less than the right value (a is smaller than b)

a <= b

Compares two values and evaluates to 1 if the left value is less than or equal to the right value

a <> b

Compara dos valores y evalúa a 1 si no son iguales

a = b

Compara dos valores y evalúa a 1 si son iguales.

a != b

a and b are not equal

a > b

Compara dos valores y evalúa como 1 si el valor izquierdo es mayor que el valor derecho (a es mayor que b)

a >= b

Compara dos valores y evalúa a 1 si el valor de la izquierda es mayor que o igual que el valor de la derecha

a ~ b

a matches the regular expression b

||

Joins two values together into a string. If one of the values is NULL the result will be NULL

“\n”

Inserta una nueva línea en una cadena

LIKE

Devuelve 1 si el primer parámetro coincide con el patrón provisto

ILIKE

Returns 1 if the first parameter matches case-insensitive the supplied pattern (ILIKE can be used instead of LIKE to make the match case-insensitive)

a IS b

Tests whether two values are identical. Returns 1 if a is the same as b

a OR b

Returns 1 when condition a or condition b is true

a AND b

Returns 1 when conditions a and b are true

NOT

Niega una condición

«Column_name»

Value of the field Column_name, take care to not be confused with simple quote, see below

“cadena”

a string value, take care to not be confused with double quote, see above

NULL

valor nulo

a IS NULL

a no tiene valor

a IS NOT NULL

a tiene valor

a IN (value[,value])

a esta debajo de los valores listados

a NOT IN (valor[,valor])

a no está debajo de los valores listados

Algún ejemplo:

  • Une una cadena de texto y un valor de un nombre de columna:

    'My feature''s id is: ' || "gid"
    
  • Test if the «description» attribute field starts with the “Hello” string in the value (note the position of the % character):

    "description" LIKE 'Hello%'
    

Processing Functions

This group contains functions that operate on processing algorithms.

Función

Descripción

parameter

Returns the value of a processing algorithm input parameter

Rasters Functions

This group contains functions to operate on raster layer.

Función

Descripción

raster_statistic

Returns statistics from a raster layer

raster_value

Returns the raster band value at the provided point

Record and Attributes Functions

Este grupo contiene funciones que operan sobre identificadores de registros.

Función

Descripción

$currentfeature

Devuelve el objeto espacial que está siendo evaluado. Se puede usar con la función “attribute” para evaluar los valores de atributo del objeto actual.

$id

Devuelve el ID del objeto de la fila actual

atributo

Devuelve el valor del atributo especificado de un objeto

attributes

Returns a map of all attributes from a feature, with field names as map keys

get_feature

Devuelve el primer objeto de una capa que coincide con un valor de atributo dado

get_feature_by_id

Returns the feature of a layer matching the given feature ID

is_selected

Returns if a feature is selected

num_selected

Returns the number of selected features on a given layer

represent_value

Returns the configured representation value for a field value (convenient with some widget types)

sql_fetch_and_increment

Manage autoincrementing values in SQLite databases

uuid

Generates a Universally Unique Identifier (UUID) for each row. Each UUID is 38 characters long.

Algún ejemplo:

  • Return the first feature in layer «LayerA» whose field «id» has the same value as the field «name» of the current feature (a kind of jointure):

    get_feature( 'layerA', 'id', attribute( $currentfeature, 'name') )
    
  • Calculate the area of the joined feature from the previous example:

    area( geometry( get_feature( 'layerA', 'id', attribute( $currentfeature, 'name') ) ) )
    

Funciones de cadena

Este grupo contiene funciones que operan sobre cadenas, por ejemplo reemplazar, convertir a mayúsculas.

Función

Descripción

char

Devuelve el carácter asociado con un código unicode

concat

Concatenates several strings to one

format

Da formato a una cadena usando los argumentos proporcionados.

format_date

Formats a date type or string into a custom string format

format_number

Devuelve un número formateado con el separador local de miles (también trunca el número al número de decimales indicado)

left(string, n)

Returns a substring that contains the n leftmost characters of the string

longitud

Returns length of a string (or length of a line geometry feature)

lower

Convierte una cadena a letras minúsculas.

lpad

Returns a string padded on the left to the specified width, using the fill character

regexp_match

Returns the first matching position matching a regular expression within a string, or 0 if the substring is not found

regexp_replace

Devuelve una cadena en la que se ha remplazado la expresión regular proporcionada

regexp_substr

Devuelve la parte de una cadena que coincide con una expresión regular proporcionada

remplazar

Returns a string with the supplied string, array, or map of strings replaced by a string, an array of strings or paired values

right(cadena, n)

Devuelve una subcadena que contiene los n caracteres más a la derecha de la cadena.

rpad

Returns a string padded on the right to the specified width, using the fill character

strpos

Returns the first matching position of a substring within another string, or 0 if the substring is not found

substr

Devuelve una parte de una cadena.

Título

Convierte todas las palabras de una cadena a formato de título (todas las palabras en minúscula con la primera letra en mayúscula)

trim

Elimina todos los espacios en blanco (espacios, tabuladores, etc.) de comienzo y final de una cadena.

upper

Convierte una cadena a letras mayúsculas.

wordwrap

Returns a string wrapped to a maximum/minimum number of characters

About fields concatenation

You can concatenate strings or field values using either || or + operators or the concat function, with some special characteristics:

  • The + operator also means sum up expression, so if you have an integer (field or numeric value) operand, this can be error prone and you better use the others:

    'My feature''s id is: ' + "gid" => triggers an error as gid is an integer
    
  • When any of the arguments is a NULL value, either || or + will return a NULL value. To return the other arguments regardless the NULL value, you may want to use the concat function:

    "country_name" || NULL => NULL
    concat('My feature''s id is: ', NULL) => My feature's id is
    concat("firstname", "nickname", "lastname") => Chuck Norris (if empty nickname)
    "firstname" + "nickname" + "lastname" => NULL (if one field is empty)
    
  • For other cases, do at your convenience:

    'My country is ' + "country_name" + ' (' + "country_code" + ')'
    'My country is ' || "country_name" || ' (' || "country_code" || ')'
    concat('My country is ', "country_name", ' (', "country_code", ')')
    # All the above return: My country is France (FR)
    

Variables Functions

This group contains dynamic variables related to the application, the project file and other settings. It means that some functions may not be available according to the context:

  • from the expressionSelect Select by expression dialog

  • desde calculateField Calculadora de campos dialog

  • desde el diálogo de propiedades de la capa

  • from the print layout

To use these functions in an expression, they should be preceded by @ character (e.g, @row_number). Are concerned:

Función

Descripción

algorithm_id

Returns the unique ID of an algorithm

atlas_feature

Devuelve el objeto del atlas actual (como objeto espacial)

atlas_featureid

Devuelve el ID de objeto del atlas actual.

atlas_featurenumber

Returns the current atlas feature number in the layout

atlas_filename

Devuelve el nombre de archivo del atlas actual.

atlas_geometry

Devuelve la geometría de objeto del atlas actual

atlas_layerid

Returns the current atlas coverage layer ID

atlas_layername

Returns the current atlas coverage layer name

atlas_pagename

Devuelve el nombre de la página del atlas actual

atlas_totalfeatures

Devuelve el número total de objetos en el atlas.

canvas_cursor_point

Returns the last cursor position on the canvas in the project’s geographical coordinates

cluster_color

Returns the color of symbols within a cluster, or NULL if symbols have mixed colors

cluster_size

Returns the number of symbols contained within a cluster

current_feature

Returns the feature currently being edited in the attribute form or table row

current_geometry

Returns the geometry of the feature currently being edited in the form or the table row

fullextent_maxx

Maximum x value from full canvas extent (including all layers)

fullextent_maxy

Maximum y value from full canvas extent (including all layers)

fullextent_minx

Minimum x value from full canvas extent (including all layers)

fullextent_miny

Minimum y value from full canvas extent (including all layers)

geometry_part_count

Returns the number of parts in rendered feature’s geometry

geometry_part_num

Returns the current geometry part number for feature being rendered

geometry_point_count

Returns the number of points in the rendered geometry’s part

geometry_point_num

Returns the current point number in the rendered geometry’s part

grid_axis

Devuelve el eje de la anotación de la cuadrícula actual (ej.: “x” para longitud, “y” para latitud).

grid_number

Devuelve el valor de anotación de la cuadrícula actual.

item_id

Returns the layout item user ID (not necessarily unique)

item_uuid

Returns the layout item unique ID

layer

Returns the current layer

layer_id

Devuelve el ID de la capa actual

layer_name

Devuelve el nombre de la capa actual

layout_dpi

Devulve la resolución de la composición (DPI).

layout_name

Returns the layout name

layout_numpages

Returns the number of pages in the layout

layout_page

Returns the page number of the current item in the layout

layout_pageheight

Returns the active page height in the layout (in mm)

layout_pagewidth

Returns the active page width in the layout (in mm)

legend_column_count

Returns the number of columns in the legend

legend_filter_by_map

Indicates if the content of the legend is filtered by the map

legend_filter_out_atlas

Indicates if the atlas is filtered out of the legend

legend_split_layers

Indicates if layers can be split in the legend

legend_title

Returns the title of the legend

legend_wrap_string

Returns the character(s) used to wrap the legend text

map_crs

Returns the Coordinate reference system of the current map

map_crs_acronym

Returns the acronym of the Coordinate reference system of the current map

map_crs_definition

Returns the full definition of the Coordinate reference system of the current map

map_crs_description

Returns the name of the Coordinate reference system of the current map

map_crs_ellipsoid

Returns the acronym of the ellipsoid of the Coordinate reference system of the current map

map_crs_proj4

Returns the Proj4 definition of the Coordinate reference system of the current map

map_crs_wkt

Returns the WKT definition of the Coordinate reference system of the current map

map_extent

Returns the geometry representing the current extent of the map

map_extent_center

Returns the point feature at the center of the map

map_extent_height

Devuelve la altura actual del mapa

map_extent_width

Devuelve el ancho actual del mapa

map_id

Returns the ID of current map destination. This will be “canvas” for canvas renders, and the item ID for layout map renders

map_layer_ids

Returns the list of map layer IDs visible in the map

map_layers

Returns the list of map layers visible in the map

map_rotation

Devuelve la rotación actual del mapa

map_scale

Devuelve la escala actual del mapa

map_units

Returns the units of map measurements

notification_message

Content of the notification message sent by the provider (available only for actions triggered by provider notifications).

parent

Refers to the current feature in the parent layer, providing access to its attributes and geometry when filtering an aggregate function

project_abstract

Returns the project abstract, taken from project metadata

project_area_units

Returns the area unit for the current project, used when calculating areas of geometries

project_author

Returns the project author, taken from project metadata

project_basename

Returns the basename of current project’s filename (without path and extension)

project_creation_date

Returns the project creation date, taken from project metadata

project_crs

Returns the Coordinate reference system of the project

project_crs_definition

Returns the full definition of the Coordinate reference system of the project

project_distance_units

Returns the distance unit for the current project, used when calculating lengths of geometries and distances

project_ellipsoid

Returns the name of the ellipsoid of the current project, used when calculating geodetic areas or lengths of geometries

project_filename

Returns the filename of the current project

project_folder

Returns the folder of the current project

project_home

Returns the home path of the current project

project_identifier

Returns the project identifier, taken from the project’s metadata

project_keywords

Returns the project keywords, taken from the project’s metadata

project_path

Returns the full path (including file name) of the current project

project_title

Devuelve el Título del proyecto actual.

qgis_locale

Returns the current language of QGIS

qgis_os_name

Devuelve el nombre del sistema operativo, ej. “Windows”, “Linux” o “OSX”.

qgis_platform

Devuelve la plataforma de QGIS, ej. “Escritorio” o “Servidor”.

qgis_release_name

Devuelve el nombre de la versión actual de QGIS

qgis_short_version

Returns current QGIS version short string

qgis_version

Devuelve la versión actual de QGIS como cadena

qgis_version_no

Devuelve la versión actual de QGIS como número

snapping_results

Gives access to snapping results while digitizing a feature (only available in add feature)

scale_value

Returns current scale bar distance value

symbol_angle

Devuelve el ángulo del símbolo usado para representar el objeto (solo válido para símbolos de marcador).

symbol_color

Returns the color of the symbol used to render the feature

symbol_count

Returns the number of features represented by the symbol (in the layout legend)

symbol_id

Returns the Internal ID of the symbol (in the layout legend)

symbol_label

Returns the label for the symbol (either a user defined label or the default autogenerated label - in the layout legend)

user_account_name

Devuelve el nombre de la cuenta del sistema operativo del usuario actual.

user_full_name

Devuelve el nombre de usuario del sistema operativo del usuario actual.

row_number

Guarda el número de la fila actual.

Valor

Devuelve el valor actual

with_variable

Allows setting a variable for usage within an expression and avoid recalculating the same value repeatedly

Algún ejemplo:

  • Return the X coordinate of a map item center to insert into a label in layout:

    x( map_get( item_variables( 'map1'), 'map_extent_center' ) )
    
  • Return for each feature in the current layer the number of overlapping airports features:

    aggregate( layer:='airport', aggregate:='count', expression:="code",
                   filter:=intersects( $geometry, geometry( @parent ) ) )
    
  • Get the object_id of the first snapped point of a line:

    with_variable(
      'first_snapped_point',
      array_first( @snapping_results ),
      attribute(
        get_feature_by_id(
          map_get( @first_snapped_point, 'layer' ),
          map_get( @first_snapped_point, 'feature_id' )
        ),
        'object_id'
      )
    )
    

Funciones recientes

This group contains recently used functions. Depending on the context of its usage (feature selection, field calculator, generic), any applied expression is added to the corresponding list (up to ten expressions), sorted from the more recent to the less one. This helps to quickly retrieve and reapply any previously used expression.

Editor de Funciones

With the Function Editor tab, you are able to write your own functions in Python language. This provides a handy and comfortable way to address particular needs that would not be covered by the predefined functions.

../../../_images/function_editor.png

La pestaña Editor de funciones

To create a new function:

  1. Press the signPlus New File button.

  2. Enter a name to use in the form that pops up and press OK.

    A new item of the name you provide is added in the left panel of the Function Editor tab; this is a Python .py file based on QGIS template file and stored in the /python/expressions folder under the active user profile directory.

  3. The right panel displays the content of the file: a python script template. Update the code and its help according to your needs.

  4. Press the start Save and Load Functions button. The function you wrote is added to the functions tree in the Expression tab, by default under the Custom group.

  5. Enjoy your new function.

  6. If the function requires improvements, enable the Function Editor tab, do the changes and press again the start Save and Load Functions button to make them available in the file, hence in any expression tab.

Custom Python functions are stored under the user profile directory, meaning that at each QGIS startup, it will auto load all the functions defined with the current user profile. Be aware that new functions are only saved in the /python/expressions folder and not in the project file. If you share a project that uses one of your custom functions you will need to also share the .py file in the /python/expressions folder.

Here’s a short example on how to create your own functions:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def my_sum(value1, value2, feature, parent):
    """
    Calculates the sum of the two parameters value1 and value2.
    <h2>Example usage:</h2>
    <ul>
      <li>my_sum(5, 8) -> 13</li>
      <li>my_sum("field1", "field2") -> 42</li>
    </ul>
    """
    return value1 + value2

The short example creates a function my_sum that will give you a function with two values. When using the args='auto' function argument the number of function arguments required will be calculated by the number of arguments the function has been defined with in Python (minus 2 - feature, and parent).

This function can then be used in expressions:

../../../_images/customFunction.png

Custom Function added to the Expression tab

Se puede encontrar más información sobre cómo crear código Python en:ref:PyQGIS-Developer-Cookbook.