表达式、筛选和计算值¶

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)或函数(返回标量值)进行计算。见 表达 在用户手册中查看可用功能的完整列表。

支持三种基本类型:

以下操作可用:

支持以下谓词:

谓词示例:

标量表达式示例:

正在分析表达式

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'

计算表达式

基本表达式


exp=qgsexpression('1+1=2')value=exp.evaluate()。

具有特征的表达式

下面的示例将根据一个特性计算给定表达式。一 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)

处理错误

exp = QgsExpression("1 + 1 = 2 ")
if exp.hasParserError():
  raise Exception(exp.parserErrorString())

value = exp.evaluate()
if exp.hasEvalError():
  raise ValueError(exp.evalErrorString())

print(value)

实例

以下示例可用于筛选层并返回与谓词匹配的任何功能。

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