Expresii¶
Based on layer data and prebuilt or user defined functions, Expressions offer a powerful way to manipulate attribute value, geometry and variables in order to dynamically change the geometry style, the content or position of the label, the value for diagram, the height of a layout item, select some features, create virtual field …
Constructorul expresiilor de tip șir¶
Main dialog to build expressions, the Expression string builder is available from many parts in QGIS and, can particularly be accessed when:
selecting features with the
Select By Expression… tool;
editing attributes with e.g. the
Field calculator tool;
manipulating symbology, label or layout item parameters with the
Data defined override tool (see Configurarea suprascrierii definită de date);
building a geometry generator symbol layer;
doing some geoprocessing.
Dialogul Constructorului de Expresii oferă acces la:
Expression tab which, thanks to a list of predefined functions, helps to write and check the expression to use;
Function Editor tab which helps to extend the list of functions by creating custom ones.
Some use cases of expressions:
De la câmp Calculator, se calculează câmpul „pop_density” folosind câmpurile existente „total_pop” și „area_km2”:
"total_pop" / "area_km2"
Actualizarea câmpului „density_level” cu categorii, în funcție de valorile „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
Aplicarea unui stil categorisit pentru toate entitățile, în funcție de prețul mediu al casei, dacă este mai mică sau mai mare de 10000€ pe metru pătrat:
"price_m2" > 10000
Folosind instrumentul de „Selectare După Expresie…”, selectați toate entitățile care reprezintă zonele cu „Densitate ridicată a populației” și în care prețul mediu pentru o casă este mai mare de 10000€ pe metru pătrat:
"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.
Sfat
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!
List of functions¶
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.
Sfat
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.
Sfat
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.
Sfat
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.

Fila Expresiilor¶
Aggregates Functions¶
This group contains functions which aggregate values over layers and fields.
Funcția |
Descriere |
---|---|
aggregate |
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 |
concatenate |
Returns the all aggregated strings from a field or expression joined by a delimiter |
count |
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 |
majority |
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 |
maximum |
Returns the aggregate maximum value from a field or expression |
mean |
Returns the aggregate mean value from a field or expression |
median |
Returns the aggregate median value from a field or expression |
min_length |
Returns the minimum length of strings from a field or expression |
minimum |
Returns the aggregate minimum value from a field or expression |
minority |
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 |
Returns the calculated third quartile from a field or expression |
range |
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 |
Exemple:
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")
sau:
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.
Funcția |
Descriere |
---|---|
array |
Returns an array containing all the values passed as parameter |
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_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 |
Funcțiile Culorilor¶
Acest grup conține funcții pentru manipularea culorilor.
Funcția |
Descriere |
---|---|
color_cmyk |
Returnează o reprezentare de tip șir a unei culori, în funcție de componentele ei cyan, magenta, galben și negru |
color_cmyka |
Returnează o reprezentare de tip șir a unei culori, în funcție de componentele ei cyan, magenta, galben, negru și alpha (transparență) |
color_grayscale_average |
Applies a grayscale filter and returns a string representation from a provided color |
color_hsl |
Returnează o reprezentare de tip șir a culorii, pe baza atributelor nuanței, saturației și luminozității |
color_hsla |
Returnează o reprezentare de tip șir a culorii, pe baza atributelor nuanței, saturației, luminozității și alpha (transparență) |
color_hsv |
Returnează o reprezentare de tip șir a culorii, pe baza atributelor nuanței, saturației și valorii |
color_hsva |
Returnează o reprezentare de tip șir a culorii, pe baza atributelor nuanței, saturației, valorii și alpha (transparență) |
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 |
Returnează o componentă specifică dintr-un șir de culoare, de exemplu, o componentă roșie sau o componentă alfa |
color_rgb |
Returnează o reprezentare de tip șir a culorii, pe baza componentelor roșie, verde și albastră |
color_rgba |
Returnează o reprezentare de tip șir a culorii, pe baza componentelor roșie, verde, albastră și alpha (transparență) |
create_ramp |
Returns a gradient ramp from a map of color strings and steps |
darker |
Returnează o culoare, de tip șir, mai închisă (sau mai deschisă) |
lighter |
Returnează o culoare, de tip șir, mai deschisă (sau mai închisă) |
project_color |
Returnează o culoare din schema de culori a proiectului |
ramp_color |
Returnează o reprezentare de tip șir a culorii, dintr-un interval de culori |
set_color_part |
Setează o componentă de culoare specifică pentru un șir de culoare, cum ar fi o componentă roșie sau o componentă alfa |
Conditional Functions¶
Acest grup conține funcții care gestionează verificările condiționale din expresii.
Funcția |
Descriere |
---|---|
CASE WHEN … THEN … END |
Evaluează o expresie și returnează un rezultat dacă este adevărat. Aveți posibilitatea să testați mai multe condiții |
CASE WHEN … THEN … ELSE … END |
Evaluează o expresie și returnează diverse rezultate, în funcție de valorile returnate, true sau false. Aveți posibilitatea de a testa mai multe condiții |
coalesce |
Returnează prima valoare non-NULL din lista de expresii |
if |
Teste o condiție și returnează un rezultat diferit, în funcție de verificarea condițională |
Câteva exemple:
Trimite înapoi o valoare în cazul în care prima condiție este adevărată, altfel, transmite o altă valoare:
CASE WHEN "software" LIKE '%QGIS%' THEN 'QGIS' ELSE 'Other' END
Conversions Functions¶
Acest grup conține funcții pentru transformarea dintr-un tip de dată în altul (ex.: din șir în întreg, din întreg în șir).
Funcția |
Descriere |
---|---|
to_date |
Convertește un șir într-un obiect de tip dată |
to_datetime |
Convertește un șir într-un obiect datetime |
to_dm |
Converts a coordinate to degree, minute |
to_dms |
Converts coordinate to degree, minute, second |
to_int |
Convertește un șir într-un număr întreg |
to_interval |
Convertește un șir într-un interval (poate fi folosit pentru a returna zilele, orele, lunile, etc dintr-o dată) |
to_real |
Convertește un șir într-un număr real |
to_string |
Convertește un număr într-un șir |
to_time |
Convertește un șir într-un obiect time |
Funcții Personalizate¶
This group contains functions created by the user. See Editorul de Funcții for more details.
Funcții pentru Dată și Oră¶
Acest grup conține funcții care gestionează datele calendaristice și ora.
Funcția |
Descriere |
---|---|
age |
Returnează diferența dintre două date sau de tip datetimes, sub formă de interval |
day |
Extrage ziua dintr-o dată sau dintr-o valoare datetime, sau numărul de zile dintr-un interval. |
day_of_week |
Returnează un număr corespunzător zilei din săptămână, pentru data sau valoarea datetime specificată |
epoch |
Returns the interval in milliseconds between the unix epoch and a given date value |
hour |
Extrage partea corespunzătoare orei dintr-o valoare datetime sau time, sau numărul de ore dintr-un interval |
minute |
Extrage partea corespunzătoare minutelor dintr-o valoare datetime sau time, sau numărul de minute dintr-un interval. |
month |
Extrage partea corespunzătoare lunii dintr-o valoare datetime sau time, sau numărul lunii dintr-un interval. |
now |
Returnează data și ora curente |
secundă |
Extrage partea corespunzătoare secundelor dintr-o valoare time sau datetime, sau numărul de secunde dintr-un interval |
week |
Extrage numărul săptămânii dintr-o valoare date sau datetime, sau numărul de săptămâni dintr-un interval |
year |
Extrage partea corespunzătoare anului dintr-o valoare datetime sau time, sau numărul de ani dintr-un interval |
This group also shares several functions with the Conversions Functions ( to_date, to_time, to_datetime, to_interval) and Funcții pentru Șiruri (format_date) groups.
Câteva exemple:
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>
Notă
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)
Fields and Values¶
Conține o listă de câmpuri dintr-un strat.
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.
Funcții pentru Potrivirea Fuzzy¶
Acest grup conține funcții pentru comparații fuzzy între valori.
Funcția |
Descriere |
---|---|
hamming_distance |
Returnează numărul de caractere la pozițiile corespunzătoare acelora din șirurilor de intrare, ale căror caractere sunt diferite |
levensheim |
Returnează numărul minim de modificări de caractere (inserări, ștersături sau înlocuiri) necesare pentru a schimba un șir într-altul. Măsoară similitudinea dintre două șiruri |
longest_common_substring |
Returnează cel mai lung subșir comun dintre două șiruri |
soundex |
Returnează reprezentarea Soundex a unui șir de caractere |
Funcții Generale¶
Acest grup conține diverse funcții generale.
Funcția |
Descriere |
---|---|
env |
Gets an environment variable and returns its content
as a string. If the variable is not found, |
eval |
Evaluează o expresie care este transmisă într-un șir. Folosește pentru a extinde parametrii dinamici transmiși ca variabile de context sau câmpuri |
is_layer_visible |
Returns true if a specified layer is visible |
layer_property |
Returnează o proprietate a unui strat sau o valoare a metadatelor sale. Aceasta poate fi numele stratului, crs-ul, tipul geometriei, numărul de entități… |
var |
Returnează valoarea stocată într-o variabilă specificată. A se vedea funcțiile variabile de mai jos |
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. |
Funcții Geometrice¶
Acest grup conține funcții care operează asupra geometriei obiectelor (de ex.: lungimea, suprafața).
Funcția |
Descriere |
---|---|
$area |
Returnează aria entității curente |
$geometry |
Returnează geometria entității curente (se poate folosi pentru prelucrarea cu alte funcții) |
$length |
Returnează lungimea entității curente de tip linie |
$perimeter |
Returnează perimetrul entității curente de tip poligon |
$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 |
Returnează aria unei entități de geometrie poligonală. Calculele sunt în Sistemul de Referință Spațială al acestei geometrii |
azimuth |
Returns the north-based azimuth as the angle in radians measured clockwise from the vertical on point_a to point_b |
boundary |
Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the geometry - see also Boundary). |
bounds |
Returns a geometry which represents the bounding box of an input geometry. Calculations are in the Spatial Reference System of this geometry (see also Bounding boxes) |
bounds_height |
Returns the height of the bounding box of a geometry. Calculations are in the Spatial Reference System of this geometry |
bounds_width |
Returns the width of the bounding box of a geometry. Calculations are in the Spatial Reference System of this geometry |
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 width buffer (by M value)) |
centroid |
Returns the geometric center of a geometry (see also Centroids) |
closest_point |
Returnează cel mai apropiat punct al unei geometrii față de o alta |
combine |
Returnează combinația a două geometrii |
contains(a,b) |
Returnează 1 (true) dacă și numai dacă nici un punct al geometriei b nu se află în exteriorul geometriei a, și cel puțin un punct din interiorul lui b se află în interiorul lui 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 Convex hull) |
crosses |
Returnează 1 (true) dacă geometriile respective au unele puncte interioare, dar nu toate, în comun |
difference(a,b) |
Returns a geometry that represents that part of geometry a that does not intersect with geometry b (see also Difference) |
disjoint |
Returnează 1 (true) dacă geometriile nu partajează nici un fel de spațiu |
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 Extract specific vertices) |
extend |
Extends the start and end of a linestring geometry by a specified amount (see also Extend lines) |
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 Swap X and Y coordinates) |
geom_from_gml |
Returnează geometria dintr-o reprezentare GML a unei geometrii |
geom_from_wkt |
Returnează o geometrie creată dintr-o reprezentare Well-Known Text (WKT) |
geom_to_wkt |
Returnează reprezentarea Well-Known Text (WKT) a unei geometrii, fără metadatele SRID |
geometrie |
Returnează geometria unei entități |
geometry_n |
Returnează geometria n dintr-o colecție de geometrii, sau null dacă geometria de intrare nu reprezintă o colecție |
hausdorff_distance |
Returns basically a measure of how similar or dissimilar 2 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 |
Returnează inel interior n dintr-o geometrie poligonală, sau null dacă geometria de intrare nu reprezintă un poligon |
intersection |
Returns a geometry that represents the shared portion of two geometries (see also Intersection) |
intersects |
Testează dacă o geometrie intersectează o alta. Returnează 1 (true) dacă geometriile se intersectează spațial (partajează oricare parte din spațiu) și 0 în caz contrar |
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 |
length |
Returnează lungimea unei entități cu geometria de tip linie (sau lungimea unui șir de caractere) |
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 Interpolate point on line) |
line_locate_point |
Returns the distance along a linestring corresponding to the closest position the linestring comes to a specified point geometry. |
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 Line substring) |
line_merge |
Returns a (Multi-)LineString geometry, where any connected LineStrings from the input geometry have been merged into a single linestring. |
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 |
Creează o geometrie de tip linie, dintr-o serie de geometrii de tip punct |
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 |
Creează o geometrie de tip poligon, dintr-un inel exterior și dintr-o serie de geometrii inelare interioare |
make_regular_polygon |
Creates a regular polygon |
make_triangle |
Creates a triangle polygon |
minimal_circle |
Returns the minimal enclosing circle of an input geometry (see also Minimum enclosing circles) |
nodes_to_points |
Returns a multipoint geometry consisting of every node in the input geometry (see also Extract vertices) |
num_geometries |
Returnează numărul de geometrii dintr-o colecție geometrică, sau null dacă geometria de intrare nu reprezintă o colecție |
num_interior_rings |
Returnează numărul de inele interioare dintr-un poligon sau dintr-o colecție geometrică, sau null dacă geometria de intrare nu reprezintă un poligon sau o colecție |
num_points |
Returnează numărul de vertecși dintr-o geometrie |
num_rings |
Returnează numărul de inele (incluzând inelele exterioare) dintr-un poligon sau dintr-o colecție geometrică, sau null dacă geometria de intrare nu reprezintă un poligon sau o colecție |
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 Offset lines) |
order_parts |
Ordonează părțile unei MultiGeometrii după anumite criterii |
oriented_bbox |
Returns a geometry representing the minimal oriented bounding box of an input geometry (see also Oriented minimum bounding box) |
overlaps |
Testează dacă o geometrie se suprapune peste alta. Returnează 1 (true) dacă geometriile partajează un spațiu, sunt de aceeași dimensiune, dar nu sunt complet conținute una în cealaltă |
perimeter |
Returnează perimetrul unei entități de geometrie poligonală. Calculele sunt în Sistemul de Referință Spațială al acestei geometrii |
point_n |
Returns a specific node from a geometry (see also Extract specific vertices) |
point_on_surface |
Returns a point guaranteed to lie on the surface of a geometry (see also Point on Surface) |
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 Pole of inaccessibility) |
proiect |
Returns a point projected from a start point using a distance and bearing (azimuth) in radians (see also Project points (Cartesian)) |
relate |
Testează sau returnează Modelul Dimensional Extins cu 9 Intersecții (DE-9IM), de reprezentare a relațiilor dintre două geometrii |
reverse |
Reverses the direction of a line string by reversing the order of its vertices (see also Reverse line direction) |
segments_to_lines |
Returns a multi line geometry consisting of a line for every segment in the input geometry (see also Explode lines) |
shortest_line |
Returnează cea mai scurtă linie care unește două geometrii. Linia rezultată va începe la geometria 1 și se va încheia la geometria 2 |
simplify |
Simplifies a geometry by removing nodes using a distance based threshold (see also Simplify) |
simplify_vw |
Simplifies a geometry by removing nodes using an area based threshold (see also Simplify) |
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 Single sided buffer) |
smooth |
Smooths a geometry by adding extra nodes which round off corners in the geometry (see also Smooth) |
start_point |
Returns the first node from a geometry (see also Extract specific vertices) |
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) |
touches |
Testează dacă o geometrie o atinge pe alta. Returnează 1 (true) dacă geometriile respective au cel puțin un punct în comun, dar interioarele lor nu se intersectează |
transform |
Returns the geometry transformed from the source CRS to the destination CRS (see also Reproject layer) |
translate |
Returns a translated version of a geometry. Calculations are in the Spatial Reference System of the geometry (see also Translate) |
union |
Returnează o geometrie care reprezintă setul de puncte reunit al geometriilor |
wedge_buffer |
Returns a wedge shaped buffer originating from a point geometry given an angle and radii (see also Create wedge buffers) |
within (a,b) |
Testează dacă o geometrie este conținută în alta. Returnează 1 (true) dacă geometria a este complet inclusă în geometria b |
x |
Returns the X coordinate of a point geometry, or the X coordinate of the centroid for a non-point geometry |
x_min |
Returns the minimum X coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry |
x_max |
Returns the maximum 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_min |
Returns the minimum Y coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry |
y_max |
Returns the maximum Y coordinate of a geometry. Calculations are in the Spatial Reference System of this geometry |
z |
Returns the Z coordinate of a point geometry |
Câteva exemple:
You can manipulate the current geometry with the variable $geometry to create a buffer or get the point on surface:
buffer( $geometry, 10 ) point_on_surface( $geometry )
Return the X coordinate of the current feature’s centroid:
x( $geometry )
Trimite înapoi o valoare în funcție de suprafața entității:
CASE WHEN $area > 10 000 THEN 'Larger' ELSE 'Smaller' END
Layout Functions¶
This group contains functions to manipulate print layout items properties.
Funcția |
Descriere |
---|---|
item_variables |
Returns a map of variables from a layout item inside this print layout |
Câteva exemple:
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.
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.
Funcția |
Descriere |
---|---|
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 |
Funcțiile Matematice¶
Acest grup conține funcții matematice (ex.: rădăcina pătrată, sin și cos).
Funcția |
Descriere |
---|---|
abs |
Returnează valoarea absolută a unui număr |
acos |
Returnează cosinusul invers al unei valori, în radiani |
asin |
Returnează sinusul invers al unei valori, în radiani |
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) |
Returnează azimutul, în funcție de nord, ca unghiul măsurat în radiani, în sens orar, pe verticală, de la punctul a la punctul b |
ceil |
Rotunjește în sus un număr |
clamp |
Restricționează într-un interval specificat o valoare de intrare |
cos |
Returnează cosinusul unei valori, în radiani |
degrees |
Convertește din radiani în grade |
exp |
Returnează exponentul unei valori |
floor |
Rotunjește în jos un număr |
inclination |
Returns the inclination measured from the zenith (0) to the nadir (180) on point_a to point_b. |
ln |
Returnează logaritmul natural al expresiei transmise |
log |
Returnează valoarea logaritmului pentru valoarea și baza transmise |
log10 |
Returnează valoarea logaritmului în baza 10 pentru expresia transmisă |
max |
Returns the largest not null value in a set of values |
min |
Returns the smallest not null value in a set of values |
pi |
Returnează valoarea pi, pentru calcule |
radians |
Convertește din grade în radiani |
rand |
Returnează un număr aleator întreg, în intervalul specificat de argumentele minim și maxim (inclusiv). |
randf |
Returnează un număr aleator zecimal, în intervalul specificat de argumentele minim și maxim (inclusiv) |
round |
Rotunjește la numărul de poziții zecimale |
scale_exp |
Transformă o valoare dată dintr-un domeniu de intrare la un interval de ieșire, folosind o curbă exponențială |
scale_linear |
Transformă o valoare dată dintr-un domeniu de intrare la un interval de ieșire, folosind o interpolare liniară |
sin |
Returnează sinusul unui unghi |
sqrt |
Returnează rădăcina pătrată a unei valori |
tan |
Returnează tangenta unui unghi |
Operatori¶
Acest grup cuprinde operatorii (ex.: +, -, *). De notat că pentru majoritatea funcțiilor matematice de mai jos, în cazul în care una dintre intrări are valoarea NULL, atunci rezultatul este NULL.
Funcția |
Descriere |
---|---|
a + b |
Adunarea a două valori (a plus b) |
a - b |
Scăderea a două valori (a minus b) |
a * b |
Înmulțirea a două valori (a înmulțit cu b) |
a / b |
Împărțirea a două valori (a împărțit la b) |
a % b |
Restul împărțirii lui a la b (ex.: 7 % 2 = 1, sau 2 se potrivește de trei ori în 7, având restul 1) |
a ^ b |
Puterea a două valori (de exemplu, 2^2=4 or 2^3=8) |
a < b |
Compară două valori și le evaluează la 1, dacă valoarea din stânga este mai mică decât cea din dreapta. (a este mai mic decât b) |
a <= b |
Compares two values and evaluates to 1 if the left value isless than or equal to the right value |
a <> b |
Compară două valori, și le evaluează la 1 dacă acestea nu sunt egale |
a = b |
Compară două valori și le evaluează la 1, dacă acestea sunt egale |
a != b |
a și b nu sunt egale |
a > b |
Compară două valori și le evaluează la 1, dacă valoarea din stânga este mai mare decât cea din dreapta (a este mai mare decât b) |
a >= b |
Compară două valori și le evaluează la 1, dacă valoarea din stânga este mai mare sau egală cu cea din dreapta |
a ~ b |
a se potrivește cu expresia regulată b |
|| |
Îmbină două valori într-un șir. Dacă una dintre valori este NULL, atunci rezultatul va fi NULL. |
«\n» |
Introduce o nouă linie într-un șir |
LIKE |
Returnează 1 dacă primul parametru se potrivește cu modelul furnizat |
ILIKE |
Returnează 1 dacă primul parametru se potrivește, în mod insensibil la context, cu modelul furnizat. (ILIKE poate fi folosit în loc de LIKE, pentru a realiza o identificare insensibilă la context) |
a IS b |
Stabilește dacă două valori sunt identice. Returnează 1 dacă a este similar cu 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 |
Neagă o condiție |
nume de coloană „numele coloanei” |
Valoarea din câmpul reprezentat de numele coloanei; a se vedea mai jos, pentru a nu face confuzie cu ghilimelele simple |
«șir» |
o valoare de tip șir; a se vedea mai sus, pentru a nu face confuzie cu ghilimelele duble |
NULL |
valoarea NULL |
a IS NULL |
a nu are nici o valoare |
a IS NOT NULL |
a are o valoare |
a IN (value[,value]) |
a se află în lista de valori |
a NOT IN (value[,value]) |
a nu se află în lista de valori |
Notă
About fields concatenation
You can concatenate strings using either || or +
. The latter also means
sum up expression. So if you have an integer (field or numeric value) this can
be error prone. In this case, you should use ||. If you concatenate two
string values, you can use both.
Câteva exemple:
Îmbină un șir cu o valoare din numele unei coloane:
'My feature''s id is: ' || "gid" 'My feature''s id is: ' + "gid" => triggers an error as gid is an integer "country_name" + '(' + "country_code" + ')' "country_name" || '(' || "country_code" || ')'
Testați dacă atributul câmpului „description” începe cu șirul «Hello» (notați poziția caracterului %):
"description" LIKE 'Hello%'
Rasters Functions¶
This group contains functions to operate on raster layer.
Funcția |
Descriere |
---|---|
raster_statistic |
Returns statistics from a raster layer |
raster_value |
Returns the raster band value at the provided point |
Record and Attributes Functions¶
Acest grup conține funcții care operează asupra identificatorilor de înregistrare.
Funcția |
Descriere |
---|---|
$currentfeature |
Returnează entitatea care este evaluată în mod curent. Se poate utiliza cu funcția «atribut» pentru a evalua valorile atributelor din entitatea curentă. |
$id |
Returnează id-ul entității din rândul curent |
atribut |
Returns the value of a specified attribute from a feature |
get_feature |
Returns the first feature of a layer matching a given attribute value |
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) |
uuid |
Generates a Universally Unique Identifier (UUID) for each row. Each UUID is 38 characters long. |
Câteva exemple:
Returnează prima entitate din stratul „LayerA”, al cărui câmp „id” are aceeași valoare ca și câmpul „nume” al entității curente (un fel de relație):
get_feature( 'layerA', 'id', attribute( $currentfeature, 'name') )
Se calculează aria entității îmbinate, din exemplul anterior:
area( geometry( get_feature( 'layerA', 'id', attribute( $currentfeature, 'name') ) ) )
Funcții pentru Șiruri¶
Acest grup conține funcții care operează asupra șirurilor, (de ex: înlocuirea, conversia în majuscule).
Funcția |
Descriere |
---|---|
char |
Returns the character associated with a unicode code |
concat |
Concatenează mai multe șiruri într-unul |
format |
Formatează un șir folosind argumentele furnizate |
format_date |
Formatează un tip de dată sau un șir într-un format personalizat de tip text |
format_number |
Returnează un număr formatat, cu separatorul local pentru mii (trunchiază, de asemenea, la numărul de cifre specificate) |
left(string, n) |
Returnează un subșir care conține n caractere din stânga șirului |
length |
Returnează lungimea unui șir (sau lungimea unei entități cu geometria de tip linie) |
lower |
Convertește un șir în litere mici |
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 |
Returnează șirul înlocuit cu expresia regulată furnizată |
regexp_substr |
Returnează porțiunea dintr-un șir care se potrivește cu expresia regulată specificată |
replace |
Returns a string with the supplied string, array, or map of strings replaced by a string, an array of strings or paired values |
right(string, n) |
Returnează un subșir care conține n caractere din stânga șirului |
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 |
Returnează o parte dintr-un șir |
title |
Convertește, în nume proprii, toate cuvintele unui șir (toate cuvintele fiind scrise cu minuscule, având o majusculă la început). |
trim |
Elimină toate spațiile albe de la începutul și de la sfârșitul unui șir (spații, tab-uri, etc) |
upper |
Convertește un șir în majuscule. |
wordwrap |
Returnează un șir cu un număr maxim/minim de caractere per linie |
Funcții Variabile¶
Acest grup cuprinde variabile dinamice referitoare la aplicație, fișierul de proiect și alte setări. Aceasta înseamnă că anumite funcții pot nu fie disponibile, în funcție de context:
din dialogul cu proprietățile stratului
from the print layout
Pentru a utiliza aceste funcții într-o expresie, acestea ar trebui să fie precedate de caracterul @ (ex.: @row_number). Sunt luate în considerare:
Funcția |
Descriere |
---|---|
algorithm_id |
Returns the unique ID of an algorithm |
atlas_feature |
Returnează entitatea curentă a atlasului (ca obiect entitate) |
atlas_featureid |
Returnează ID-ul entității curente a atlasului |
atlas_featurenumber |
Returns the current atlas feature number in the layout |
atlas_filename |
Returnează numele curent al fișierului atlasului |
atlas_geometry |
Returnează geometria entității curente a atlasului |
atlas_layerid |
Returns the current atlas coverage layer ID |
atlas_layername |
Returns the current atlas coverage layer name |
atlas_pagename |
Returnează numele paginii curente a atlasului |
atlas_totalfeatures |
Returnează numărul total de entități din 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 |
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 |
Returnează axele actuale ale adnotării din grilă (de exemplu, «x» pentru longitudine, «y» pentru latitudine) |
grid_number |
Returnează valoarea actuală a adnotării din grilă |
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 |
Returnează ID-ul stratului curent |
layer_name |
Returnează numele stratului curent |
layout_dpi |
Returnează rezoluția compoziției (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) |
map_crs |
Returns 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_extent |
Returns the geometry representing the current extent of the map |
map_extent_center |
Returnează entitatea de tip punct din centrul hărții |
map_extent_height |
Returnează înalțimea curentă a hărții |
map_extent_width |
Returnează lățimea curentă a hărții |
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 |
Returnează rotația curentă a hărții |
map_scale |
Returnează scara curentă a hărții |
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_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_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 |
Returnează titlul proiectului curent |
qgis_locale |
Returns the current language of QGIS |
qgis_os_name |
Returnează numele Sistemului de Operare curent, ex.: «windows», «linux» sau «osx» |
qgis_platform |
Returnează platforma QGIS, ex.: «desktop» sau «server» |
qgis_release_name |
Returnează numele versiunii curente de QGIS |
qgis_short_version |
Returns current QGIS version short string |
qgis_version |
Returnează textul versiunii curente de QGIS |
qgis_version_no |
Returnează numărul versiunii curente de QGIS |
snapping_results |
Gives access to snapping results while digitizing a feature (only available in add feature) |
symbol_angle |
Returnează unghiul simbolului utilizat pentru randarea entității (valabil numai pentru însemnele simbolurilor) |
symbol_color |
Returnează culoarea simbolului utilizat pentru a randa entitatea |
user_account_name |
Returnează numele de cont al utilizatorului curent din sistemul de operare |
user_full_name |
Returnează numele utilizatorului curent din sistemul de operare |
row_number |
Stochează numărul rândului curent |
valoare |
Returnează valoarea curentă |
with_variable |
Allows setting a variable for usage within an expression and avoid recalculating the same value repeatedly |
Câteva exemple:
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' ) )
Funcții Recente¶
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.
Editorul de Funcții¶
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.

Fila Editorului de Funcții¶
To create a new function:
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.The right panel displays the content of the file: a python script template. Update the code and its help according to your needs.
Press the
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.Enjoy your new function.
If the function requires improvements, enable the Function Editor tab, do the changes and press again the
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.
Iată un scurt exemplu cu privire la modul de creare a propriilor funcții:
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:

Custom Function added to the Expression tab¶
Mai multe informații despre crearea de cod Python pot fi găsite în Cartea de rețete a dezvoltatorului PyQGIS.