Saturday, 11 August 2018

How to get layer variables using QGIS Python APIs?



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


QGIS Layer Variable



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.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...