The code snippets on this page need the following imports if you’re outside the pyqgis console:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from qgis.core import (
edit,
QgsExpression,
QgsExpressionContext,
QgsFeature,
QgsFeatureRequest,
QgsField,
QgsFields,
QgsVectorLayer,
QgsPointXY,
QgsGeometry,
QgsProject,
QgsExpressionContextUtils
)
|
11. Выражения, фильтрация и вычисление значений¶
QGIS has some support for parsing of SQL-like expressions. Only a small subset of SQL syntax is supported. The expressions can be evaluated either as boolean predicates (returning True or False) or as functions (returning a scalar value). See Expressions in the User Manual for a complete list of available functions.
Поддерживается три основных типа данных:
число — как целые, так и десятичные, например,
123
,3.14
строка — должна заключаться в одинарные кавычки:
'hello world'
ссылка на столбец — при вычислении ссылка заменяется на значение поля. Имена полей не экранируются.
Доступны следующие операции:
арифметические операторы:
+
,-
,*
,/
,^
скобки: для изменения приоритета операций:
(1 + 1) * 3
унарный плюс и минус:
-12
,+5
математические функции:
sqrt
,sin
,cos
,tan
,asin
,acos
,atan
conversion functions:
to_int
,to_real
,to_string
,to_date
геометрические функции:
$area
,$length
geometry handling functions:
$x
,$y
,$geometry
,num_geometries
,centroid
And the following predicates are supported:
сравнение:
=
,!=
,>
,>=
,<
,<=
соответствие образцу:
LIKE
(using % and _),~
(регулярные выражения)огические операторы:
AND
,OR
,NOT
проверка на NULL:
IS NULL
,IS NOT NULL
Примеры предикатов:
1 + 2 = 3
sin(angle) > 0
'Hello' LIKE 'He%'
(x > 10 AND y > 10) OR z = 0
Примеры скалярных выражений:
2 ^ 10
sqrt(val)
$length + 1
11.1. Разбор выражений¶
The following example shows how to check if a given expression can be parsed correctly:
1 2 3 4 5 6 7 | exp = QgsExpression('1 + 1 = 2')
assert(not exp.hasParserError())
exp = QgsExpression('1 + 1 = ')
assert(exp.hasParserError())
assert(exp.parserErrorString() == '\nsyntax error, unexpected $end')
|
11.2. Вычисление выражений¶
Expressions can be used in different contexts, for example to filter features or to compute new field values. In any case, the expression has to be evaluated. That means that its value is computed by performing the specified computational steps, which can range from simple arithmetic to aggregate expressions.
11.2.1. Простые выражения¶
This basic expression evaluates to 1, meaning it is true:
exp = QgsExpression('1 + 1 = 2')
assert(exp.evaluate()) # exp.evaluate() returns 1 and assert() recognizes this as True
11.2.2. Выражения с объектами¶
To evaluate an expression against a feature, a QgsExpressionContext
object has to be created and passed to the evaluate function in order to allow the expression to access
the feature’s field values.
The following example shows how to create a feature with a field called «Column» and how to add this feature to the expression context.
1 2 3 4 5 6 7 8 9 10 11 | fields = QgsFields()
field = QgsField('Column')
fields.append(field)
feature = QgsFeature()
feature.setFields(fields)
feature.setAttribute(0, 99)
exp = QgsExpression('"Column"')
context = QgsExpressionContext()
context.setFeature(feature)
assert(exp.evaluate(context) == 99)
|
The following is a more complete example of how to use expressions in the context of a vector layer, in order to compute new field values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | from qgis.PyQt.QtCore import QVariant
# create a vector layer
vl = QgsVectorLayer("Point", "Companies", "memory")
pr = vl.dataProvider()
pr.addAttributes([QgsField("Name", QVariant.String),
QgsField("Employees", QVariant.Int),
QgsField("Revenue", QVariant.Double),
QgsField("Rev. per employee", QVariant.Double),
QgsField("Sum", QVariant.Double),
QgsField("Fun", QVariant.Double)])
vl.updateFields()
# add data to the first three fields
my_data = [
{'x': 0, 'y': 0, 'name': 'ABC', 'emp': 10, 'rev': 100.1},
{'x': 1, 'y': 1, 'name': 'DEF', 'emp': 2, 'rev': 50.5},
{'x': 5, 'y': 5, 'name': 'GHI', 'emp': 100, 'rev': 725.9}]
for rec in my_data:
f = QgsFeature()
pt = QgsPointXY(rec['x'], rec['y'])
f.setGeometry(QgsGeometry.fromPointXY(pt))
f.setAttributes([rec['name'], rec['emp'], rec['rev']])
pr.addFeature(f)
vl.updateExtents()
QgsProject.instance().addMapLayer(vl)
# The first expression computes the revenue per employee.
# The second one computes the sum of all revenue values in the layer.
# The final third expression doesn’t really make sense but illustrates
# the fact that we can use a wide range of expression functions, such
# as area and buffer in our expressions:
expression1 = QgsExpression('"Revenue"/"Employees"')
expression2 = QgsExpression('sum("Revenue")')
expression3 = QgsExpression('area(buffer($geometry,"Employees"))')
# QgsExpressionContextUtils.globalProjectLayerScopes() is a convenience
# function that adds the global, project, and layer scopes all at once.
# Alternatively, those scopes can also be added manually. In any case,
# it is important to always go from “most generic” to “most specific”
# scope, i.e. from global to project to layer
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(vl))
with edit(vl):
for f in vl.getFeatures():
context.setFeature(f)
f['Rev. per employee'] = expression1.evaluate(context)
f['Sum'] = expression2.evaluate(context)
f['Fun'] = expression3.evaluate(context)
vl.updateFeature(f)
print( f['Sum'])
|
876.5
11.2.3. Filtering a layer with expressions¶
Следующие примеры могут использоваться для фильтрации слоя и возвращения объектов, удовлетворяющих условию.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | layer = QgsVectorLayer("Point?field=Test:integer",
"addfeat", "memory")
layer.startEditing()
for i in range(10):
feature = QgsFeature()
feature.setAttributes([i])
assert(layer.addFeature(feature))
layer.commitChanges()
expression = 'Test >= 3'
request = QgsFeatureRequest().setFilterExpression(expression)
matches = 0
for f in layer.getFeatures(request):
matches += 1
assert(matches == 7)
|
11.3. Handling expression errors¶
Expression-related errors can occur during expression parsing or evaluation:
1 2 3 4 5 6 7 | exp = QgsExpression("1 + 1 = 2")
if exp.hasParserError():
raise Exception(exp.parserErrorString())
value = exp.evaluate()
if exp.hasEvalError():
raise ValueError(exp.evalErrorString())
|