Outdated version of the documentation. Find the latest one here.

Expressions, Filtering and Calculating Values

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

Trois types basiques sont supportés :

  • number — both whole numbers and decimal numbers, e.g. 123, 3.14
  • string — they have to be enclosed in single quotes: 'hello world'
  • column reference — when evaluating, the reference is substituted with the actual value of the field. The names are not escaped.

Les opérations suivantes sont disponibles:

  • opérateurs arithmétiques: +, -, *, /, ^

  • parentheses: for enforcing the operator precedence: (1 + 1) * 3
  • unary plus and minus: -12, +5
  • fonctions mathématiques: sqrt, sin, cos, tan, asin, acos, atan

  • fonctions géométriques: $area, $length

  • fonctions de conversion: to int, to real, to string

Et les prédicats suivants sont pris en charge:

  • comparaison: =, !=, >, >=, <, <=

  • pattern matching: LIKE (using % and _), ~ (regular expressions)
  • prédicats logiques: AND, OR, NOT

  • NULL value checking: IS NULL, IS NOT NULL

Exemples de prédicats:

  • 1 + 2 = 3
  • sin(angle) > 0
  • 'Hello' LIKE 'He%'
  • (x > 10 AND y > 10) OR z = 0

Exemples d’expressions scalaires:

  • 2 ^ 10
  • sqrt(val)
  • $length + 1

Parsing Expressions

>>> exp = QgsExpression('1 + 1 = 2')
>>> exp.hasParserError()
False
>>> exp = QgsExpression('1 + 1 = ')
>>> exp.hasParserError()
True
>>> exp.parserErrorString()
PyQt4.QtCore.QString(u'syntax error, unexpected $end')

Évaluation des expressions

Expressions basiques

>>> exp = QgsExpression('1 + 1 = 2')
>>> value = exp.evaluate()
>>> value
1

Expressions with features

L’exemple suivant évaluera l’expression renseignée sur chaque entité. “Colonne” est le nom du champ de la couche.

>>> exp = QgsExpression('Column = 99')
>>> value = exp.evaluate(feature, layer.pendingFields())
>>> bool(value)
True

You can also use QgsExpression.prepare() if you need check more than one feature. Using QgsExpression.prepare() will increase the speed that evaluate takes to run.

>>> exp = QgsExpression('Column = 99')
>>> exp.prepare(layer.pendingFields())
>>> value = exp.evaluate(feature)
>>> bool(value)
True

Gestion des erreurs

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

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

print value

Exemples

L’exemple suivant peut être utilisé pour filtrer une couche et ne renverra que les entités qui correspondent au prédicat.

def where(layer, exp):
  print "Where"
  exp = QgsExpression(exp)
  if exp.hasParserError():
    raise Expection(exp.parserErrorString())
  exp.prepare(layer.pendingFields())
  for feature in layer.getFeatures():
    value = exp.evaluate(feature)
    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"