[QGIS-Developer] Enable variables in QgsPropertyOverrideButton with python

Nyall Dawson nyall.dawson at gmail.com
Thu Oct 17 16:07:01 PDT 2019

On Fri, 18 Oct 2019 at 06:29, Simon Gröchenig
<simon.groechenig at salzburgresearch.at> wrote:
> Hi,
> I want to add a QgsPropertyOverrideButton to define a expression to filter features in a python plugin. Specifically, I want to filter the features using the @altas_feature variable. However, all variables are missing in the expression dialog.
> Can anyone tell me how I can add the variables to the expression dialog?

Hi Simon,

This is all controlled via expression contexts. There's a few parts to
the puzzle:

1. Crafting an appropriate expression context using the individual
"scope" creation functions available through
QgsExpressionContextUtils. You generally start with a global, project
and layer scope, and then add additional scopes on top depending on
the "context" in which the expression will be evaluated.

So something like:

context = QgsExpressionContext()
context.appendScope( QgsExpressionContextUtils.globalScope() )
context.appendScope( QgsExpressionContextUtils.projectScope(
QgsProject.instance() ) )
context.appendScope( QgsExpressionContextUtils.atlasScope( None ) )
context.appendScope( QgsExpressionContextUtils.mapSettingsScope(
iface.mapCanvas() ) )

OR -- depending on the context -- you can get a pre-made context given
straight to you. E.g. if the expression evaluation is occurring inside
a layout item, then you must use

context = item.createExpressionContext()

instead of making your own.

So this part is very dependant on the "context" in which the
expression will be evaluated.

2. Make your dialog or widget which contains the button implement the
QgsExpressionContextGenerator interface.

3. Register your dialog/widget as the context generator for the button
by calling something like

button.registerExpressionContextGenerator( dialog )


> Regards,
> Simon
> _______________________________________________
> QGIS-Developer mailing list
> QGIS-Developer at lists.osgeo.org
> List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer
> Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer

More information about the QGIS-Developer mailing list