7

How can I access the layer variables defined by the user from QGIS Python APIs?

QGIS Layer Variable

1 Answer 1

10

You may use the QgsExpressionContextUtils() class.

More in detail, you may set a new layer variable in this way:

layer = iface.activeLayer() # or similar way for loading a layer
QgsExpressionContextUtils.setLayerVariable(layer,'your_variable', 'John')

where layer is the layer object, your_variable is the name of the variable and John is the value of the variable.

For retrieving the value of the layer variable, you can use the following line:

QgsExpressionContextUtils.layerScope(layer).variable('your_variable')

In fact, if you run:

test = QgsExpressionContextUtils.layerScope(layer).variable('your_variable')
print test

you will get:

John

as desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.