Docs in progress for 'QGIS testing'. Visit https://docs.qgis.org/3.4 for QGIS 3.4 docs and translations.
警告
Despite our constant efforts, information beyond this line may not be updated for QGIS 3. Refer to https://qgis.org/pyqgis/master for the python API documentation or, give a hand to update the chapters you know about. Thanks.
QGIS对类SQL表达式的解析有一些支持。只支持SQL语法的一小部分。表达式可以作为布尔谓词(返回true或false)或函数(返回标量值)进行计算。见 表达 在用户手册中查看可用功能的完整列表。
支持三种基本类型:
123
, 3.14
'hello world'
以下操作可用:
+
, -
, *
, /
, ^
(1 + 1) * 3
-12
, +5
sqrt
, sin
, cos
, tan
, asin
, acos
, atan
to_int
, to_real
, to_string
, to_date
$area
, $length
$x
, $y
, $geometry
, num_geometries
, centroid
支持以下谓词:
=
, !=
, >
, >=
, <
, <=
LIKE
(使用%和x) ~
(正则表达式)AND
, OR
, NOT
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
exp = QgsExpression('1 + 1 = 2')
exp.hasParserError() #will return False
exp = QgsExpression('1 + 1 = ')
exp.hasParserError() #Will return True
exp.parserErrorString() #will return 'syntax error, unexpected $end'
下面的示例将根据一个特性计算给定表达式。一 QgsExpressionContext
必须为对象添加圆点并传递,以允许表达式访问功能字段值。“column”是层中字段的名称。
exp = QgsExpression('Column')
context = QgsExpressionContext()
context.setFeature(feature)
exp.evaluate(context)
99
您也可以使用 QgsExpression.prepare()
如果需要,请检查多个功能。使用 QgsExpression.prepare()
将提高评估运行所需的速度。
exp = QgsExpression('Column')
context = QgsExpressionContext()
context.setFeature(feature)
exp.prepare(context)
exp.evaluate(feature)
以下示例可用于筛选层并返回与谓词匹配的任何功能。
def where(layer, exp):
print("Where")
exp = QgsExpression(exp)
if exp.hasParserError():
raise Exception(exp.parserErrorString())
context = QgsExpressionContext()
context.setFields(layer.fields())
exp.prepare(context)
for feature in layer.getFeatures():
context.setFeature(feature)
value = exp.evaluate(context)
if exp.hasEvalError():
raise ValueError(exp.evalErrorString())
if bool(value):
yield feature
layer = qgis.utils.iface.activeLayer()
for f in where(layer, 'Test > 1.0'):
print(f + " Matches expression")