How can I access the layer variables defined by the user from QGIS Python APIs?
1 Answer
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.