QgsExpression class
Class for parsing and evaluation of expressions (formerly called "search strings").
Contents
The expressions try to follow both syntax and semantics of SQL expressions.
Usage:
QgsExpression exp("gid*2 > 10 and type not in ('D','F')"); if (exp.hasParserError()) { // show error message with parserErrorString() and exit } QVariant result = exp.evaluate(feature, fields); if (exp.hasEvalError()) { // show error message with evalErrorString() } else { // examine the result }
Three Value Logic
Similarly to SQL, this class supports three-value logic: true/false/unknown. Unknown value may be a result of operations with missing data (NULL). Please note that NULL is different value than zero or an empty string. For example 3 > NULL returns unknown.
There is no special (three-value) 'boolean' type: true/false is represented as 1/0 integer, unknown value is represented the same way as NULL values: NULL QVariant.
Performance
For better performance with many evaluations you may first call prepare(fields) function to find out indices of columns and then repeatedly call evaluate(feature).
Type conversion
Operators and functions that expect arguments to be of a particular type automatically convert the arguments to that type, e.g. sin('2.1') will convert the argument to a double, length(123) will first convert the number to a string. Explicit conversion can be achieved with to_int, to_real, to_string functions. If implicit or explicit conversion is invalid, the evaluation returns an error. Comparison operators do numeric comparison in case both operators are numeric (int/double) or they can be converted to numeric types.
Implicit sharing
This class is implicitly shared, copying has a very low overhead. It is normally preferable to call QgsExpression( otherExpression ) instead of QgsExpression( otherExpression.expression() ). A deep copy will only be made when prepare() is called. For usage this means mainly, that you should normally keep an unprepared master copy of a QgsExpression and whenever using it with a particular QgsFeatureIterator copy it just before and prepare it using the same context as the iterator.
Implicit sharing was added in 2.14
Public types
- struct ParserError
- Details about any parser errors that were found when parsing the expression.
Public static variables
- static QStringList sBuiltinFunctions
- static QList<QgsExpressionFunction*> sFunctions
- static QList<QgsExpressionFunction*> sOwnedFunctions
- List of functions owned by the expression engine.
Public static functions
- static auto checkExpression(const QString& text, const QgsExpressionContext* context, QString& errorMessage) -> bool
- Tests whether a string is a valid expression.
- static void cleanRegisteredFunctions()
- Deletes all registered functions whose ownership have been transferred to the expression engine.
- static auto createFieldEqualityExpression(const QString& fieldName, const QVariant& value) -> QString
- Create an expression allowing to evaluate if a field is equal to a value.
- static auto evaluateToDouble(const QString& text, double fallbackValue) -> double
- Attempts to evaluate a text string as an expression to a resultant double value.
- static auto formatPreviewString(const QVariant& value, bool htmlOutput = true) -> QString
- Formats an expression result for friendly display to the user.
- static auto formatVariableHelp(const QString& description, bool showValue = true, const QVariant& value = QVariant()) -> QString
- Returns formatted help text for a variable.
- static auto functionCount() -> int
- Returns the number of functions defined in the parser.
- static auto functionIndex(const QString& name) -> int
- Returns index of the function in Functions array.
- static auto group(const QString& group) -> QString
- Returns the translated name for a function group.
- static auto helpText(QString name) -> QString
- Returns the help text for a specified function.
- static auto isFunctionName(const QString& name) -> bool
- tells whether the identifier is a name of existing function
- static auto quotedColumnRef(QString name) -> QString
- Returns a quoted column reference (in double quotes)
- static auto quotedString(QString text) -> QString
- Returns a quoted version of a string (in single quotes)
- static auto quotedValue(const QVariant& value) -> QString
- Returns a string representation of a literal value, including appropriate quotations where required.
- static auto quotedValue(const QVariant& value, QVariant::Type type) -> QString
- Returns a string representation of a literal value, including appropriate quotations where required.
- static auto referencedVariables(const QString& text) -> QSet<QString>
- This function returns variables in each expression between [% and %].
- static auto registerFunction(QgsExpressionFunction* function, bool transferOwnership = false) -> bool
- Registers a function to the expression engine.
- static auto replaceExpressionText(const QString& action, const QgsExpressionContext* context, const QgsDistanceArea* distanceArea = nullptr) -> QString
- This function replaces each expression between [% and %] in the string with the result of its evaluation with the specified context.
- static auto unregisterFunction(const QString& name) -> bool
- Unregisters a function from the expression engine.
- static auto variableHelpText(const QString& variableName) -> QString
- Returns the help text for a specified variable.
Constructors, destructors, conversion operators
- QgsExpression(const QString& expr)
- Creates a new expression based on the provided string.
- QgsExpression(const QgsExpression& other)
- Create a copy of this expression.
- QgsExpression()
- Create an empty expression.
- operator QString() const
- Automatically convert this expression to a string where requested.
Public functions
-
auto areaUnits() const -> QgsUnitTypes::
AreaUnit - Returns the desired areal units for calculations involving geomCalculator(), e.g., "$area".
-
auto distanceUnits() const -> QgsUnitTypes::
DistanceUnit - Returns the desired distance units for calculations involving geomCalculator(), e.g., "$length" and "$perimeter".
- auto dump() const -> QString
- Returns an expression string, constructed from the internal abstract syntax tree.
- auto evalErrorString() const -> QString
- Returns evaluation error.
- auto evaluate() -> QVariant
- Evaluate the feature and return the result.
- auto evaluate(const QgsExpressionContext* context) -> QVariant
- Evaluate the expression against the specified context and return the result.
- auto expression() const -> QString
- Returns the original, unmodified expression string.
-
template<class T>auto findNodes() const -> QList<const T*>
- Returns a list of all nodes of the given class which are used in this expression.
- auto geomCalculator() -> QgsDistanceArea*
- Returns calculator used for distance and area calculations (used by $length, $area and $perimeter functions only)
- auto hasEvalError() const -> bool
- Returns true if an error occurred when evaluating last input.
- auto hasParserError() const -> bool
- Returns true if an error occurred when parsing the input expression.
- auto isField() const -> bool
- Checks whether an expression consists only of a single field reference.
- auto isValid() const -> bool
- Checks if this expression is valid.
- auto needsGeometry() const -> bool
- Returns true if the expression uses feature geometry for some computation.
- auto nodes() const -> QList<const QgsExpressionNode*>
- Returns a list of all nodes which are used in this expression.
- auto operator=(const QgsExpression& other) -> QgsExpression&
- Create a copy of this expression.
- auto operator==(const QgsExpression& other) const -> bool
- Compares two expressions.
-
auto parserErrors() const -> QList<QgsExpression::
ParserError> - Returns parser error details including location of error.
- auto parserErrorString() const -> QString
- Returns parser error.
- auto prepare(const QgsExpressionContext* context) -> bool
- Gets the expression ready for evaluation - find out column indexes.
- auto referencedAttributeIndexes(const QgsFields& fields) const -> QSet<int>
- Returns a list of field name indexes obtained from the provided fields.
- auto referencedColumns() const -> QSet<QString>
- Gets list of columns referenced by the expression.
- auto referencedFunctions() const -> QSet<QString>
- Returns a list of the names of all functions which are used in this expression.
- auto referencedVariables() const -> QSet<QString>
- Returns a list of all variables which are used in this expression.
- auto rootNode() const -> const QgsExpressionNode*
- Returns root node of the expression. Root node is null is parsing has failed.
-
void setAreaUnits(QgsUnitTypes::
AreaUnit unit) - Sets the desired areal units for calculations involving geomCalculator(), e.g., "$area".
-
void setDistanceUnits(QgsUnitTypes::
DistanceUnit unit) - Sets the desired distance units for calculations involving geomCalculator(), e.g., "$length" and "$perimeter".
- void setEvalErrorString(const QString& str)
- Sets evaluation error (used internally by evaluation functions)
- void setExpression(const QString& expression)
- Set the expression string, will reset the whole internal structure.
- void setGeomCalculator(const QgsDistanceArea* calc)
- Sets the geometry calculator used for distance and area calculations in expressions.
Function documentation
static bool QgsExpression:: checkExpression(const QString& text,
const QgsExpressionContext* context,
QString& errorMessage)
Tests whether a string is a valid expression.
| Parameters | |
|---|---|
| text | string to test |
| context | optional expression context |
| errorMessage | will be filled with any error message from the validation |
| Returns | true if string is a valid expression |
static void QgsExpression:: cleanRegisteredFunctions()
Deletes all registered functions whose ownership have been transferred to the expression engine.
static QString QgsExpression:: createFieldEqualityExpression(const QString& fieldName,
const QVariant& value)
Create an expression allowing to evaluate if a field is equal to a value.
| Parameters | |
|---|---|
| fieldName | the name of the field |
| value | the value of the field |
| Returns | the expression to evaluate field equality |
The value may be null.
static double QgsExpression:: evaluateToDouble(const QString& text,
double fallbackValue)
Attempts to evaluate a text string as an expression to a resultant double value.
| Parameters | |
|---|---|
| text | text to evaluate as expression |
| fallbackValue | value to return if text can not be evaluated as a double |
| Returns | evaluated double value, or fallback value |
static QString QgsExpression:: formatPreviewString(const QVariant& value,
bool htmlOutput = true)
Formats an expression result for friendly display to the user.
| Parameters | |
|---|---|
| value | expression result to format |
| htmlOutput | set to true to allow HTML formatting, or false for plain text output |
| Returns | formatted string, may contain HTML formatting characters if htmlOutput is true |
Truncates the result to a sensible length, and presents text representations of non numeric/text types (e.g., geometries and features).
static QString QgsExpression:: formatVariableHelp(const QString& description,
bool showValue = true,
const QVariant& value = QVariant())
Returns formatted help text for a variable.
| Parameters | |
|---|---|
| description | translated description of variable |
| showValue | set to true to include current value of variable in help text |
| value | current value of variable to show in help text |
static int QgsExpression:: functionCount()
Returns the number of functions defined in the parser.
| Returns | The number of function defined in the parser. |
|---|
static QString QgsExpression:: group(const QString& group)
Returns the translated name for a function group.
| Parameters | |
|---|---|
| group | untranslated group name |
static QString QgsExpression:: helpText(QString name)
Returns the help text for a specified function.
| Parameters | |
|---|---|
| name | function name |
static QString QgsExpression:: quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes)
static QString QgsExpression:: quotedString(QString text)
Returns a quoted version of a string (in single quotes)
static QString QgsExpression:: quotedValue(const QVariant& value)
Returns a string representation of a literal value, including appropriate quotations where required.
| Parameters | |
|---|---|
| value | value to convert to a string representation |
static QString QgsExpression:: quotedValue(const QVariant& value,
QVariant::Type type)
Returns a string representation of a literal value, including appropriate quotations where required.
| Parameters | |
|---|---|
| value | value to convert to a string representation |
| type | value type |
static QSet<QString> QgsExpression:: referencedVariables(const QString& text)
This function returns variables in each expression between [% and %].
| Parameters | |
|---|---|
| text | The source string in which variables should be searched. |
static bool QgsExpression:: registerFunction(QgsExpressionFunction* function,
bool transferOwnership = false)
Registers a function to the expression engine.
| Parameters | |
|---|---|
| function | function to register |
| transferOwnership | set to true to transfer ownership of function to expression engine |
| Returns | true on successful registration |
This is required to allow expressions to utilize the function.
static QString QgsExpression:: replaceExpressionText(const QString& action,
const QgsExpressionContext* context,
const QgsDistanceArea* distanceArea = nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluation with the specified context.
| Parameters | |
|---|---|
| action | The source string in which placeholders should be replaced. |
| context | Expression context |
| distanceArea | Optional QgsDistanceArea. If specified, the QgsDistanceArea is used for distance and area conversion |
Additional substitutions can be passed through the substitutionMap parameter
static bool QgsExpression:: unregisterFunction(const QString& name)
Unregisters a function from the expression engine.
| Parameters | |
|---|---|
| name | function name |
The function will no longer be usable in expressions.
static QString QgsExpression:: variableHelpText(const QString& variableName)
Returns the help text for a specified variable.
| Parameters | |
|---|---|
| variableName | name of variable |
QgsExpression:: QgsExpression(const QString& expr)
Creates a new expression based on the provided string.
The string will immediately be parsed. For optimization prepare() should always be called before every loop in which this expression is used.
QgsExpression:: QgsExpression(const QgsExpression& other)
Create a copy of this expression.
This is preferred over recreating an expression from a string since it does not need to be re-parsed.
QgsExpression:: QgsExpression()
Create an empty expression.
QgsExpression:: operator QString() const
Automatically convert this expression to a string where requested.
QgsUnitTypes:: AreaUnit QgsExpression:: areaUnits() const
Returns the desired areal units for calculations involving geomCalculator(), e.g., "$area".
QgsUnitTypes:: DistanceUnit QgsExpression:: distanceUnits() const
Returns the desired distance units for calculations involving geomCalculator(), e.g., "$length" and "$perimeter".
QString QgsExpression:: dump() const
Returns an expression string, constructed from the internal abstract syntax tree.
This does not contain any nice whitespace formatting or comments. In general it is preferable to use expression() instead.
QVariant QgsExpression:: evaluate()
Evaluate the feature and return the result.
QVariant QgsExpression:: evaluate(const QgsExpressionContext* context)
Evaluate the expression against the specified context and return the result.
| Parameters | |
|---|---|
| context | context for evaluating expression |
QString QgsExpression:: expression() const
Returns the original, unmodified expression string.
If there was none supplied because it was constructed by sole API calls, dump() will be used to create one instead.
template<class T>
QList<const T*> QgsExpression:: findNodes() const
Returns a list of all nodes of the given class which are used in this expression.
QgsDistanceArea* QgsExpression:: geomCalculator()
Returns calculator used for distance and area calculations (used by $length, $area and $perimeter functions only)
bool QgsExpression:: isField() const
Checks whether an expression consists only of a single field reference.
bool QgsExpression:: isValid() const
Checks if this expression is valid.
A valid expression could be parsed but does not necessarily evaluate properly.
QList<const QgsExpressionNode*> QgsExpression:: nodes() const
Returns a list of all nodes which are used in this expression.
QgsExpression& QgsExpression:: operator=(const QgsExpression& other)
Create a copy of this expression.
This is preferred over recreating an expression from a string since it does not need to be re-parsed.
bool QgsExpression:: operator==(const QgsExpression& other) const
Compares two expressions.
The operator returns true if the expression string is equal.
QList<QgsExpression:: ParserError> QgsExpression:: parserErrors() const
Returns parser error details including location of error.
bool QgsExpression:: prepare(const QgsExpressionContext* context)
Gets the expression ready for evaluation - find out column indexes.
| Parameters | |
|---|---|
| context | context for preparing expression |
QSet<int> QgsExpression:: referencedAttributeIndexes(const QgsFields& fields) const
Returns a list of field name indexes obtained from the provided fields.
QSet<QString> QgsExpression:: referencedColumns() const
Gets list of columns referenced by the expression.
QSet<QString> QgsExpression:: referencedFunctions() const
Returns a list of the names of all functions which are used in this expression.
QSet<QString> QgsExpression:: referencedVariables() const
Returns a list of all variables which are used in this expression.
If the list contains a NULL QString, there is a variable name used which is determined at runtime.
void QgsExpression:: setAreaUnits(QgsUnitTypes:: AreaUnit unit)
Sets the desired areal units for calculations involving geomCalculator(), e.g., "$area".
void QgsExpression:: setDistanceUnits(QgsUnitTypes:: DistanceUnit unit)
Sets the desired distance units for calculations involving geomCalculator(), e.g., "$length" and "$perimeter".
void QgsExpression:: setExpression(const QString& expression)
Set the expression string, will reset the whole internal structure.
void QgsExpression:: setGeomCalculator(const QgsDistanceArea* calc)
Sets the geometry calculator used for distance and area calculations in expressions.
| Parameters | |
|---|---|
| calc | geometry calculator. Ownership is not transferred. Set to a nullptr to force Cartesian calculations. |
(used by $length, $area and $perimeter functions only). By default, no geometry calculator is set and all distance and area calculations are performed using simple Cartesian methods (ie no ellipsoidal calculations).
Variable documentation
static QStringList QgsExpression:: sBuiltinFunctions
static QList<QgsExpressionFunction*> QgsExpression:: sFunctions
static QList<QgsExpressionFunction*> QgsExpression:: sOwnedFunctions
List of functions owned by the expression engine.