Sunday, 24 November 2019

qgis - How to change a project variable using Python?


I'd like to change the value of a user-defined project variable (can be manually edited in Project Settings | Variables) using the Python console. I tracked down the setVariable() function in the QgsExpressionContextScope class but haven't succeeded in actually changing the variable in the project settings. My code so far:


iface.mapCanvas().mapSettings().expressionContext().scope(0).setVariable('myvar',1)

I guess I'm getting lost in the different expression contexts ...



Answer



Look at QgsExpressionContextUtils (https://qgis.org/api/classQgsExpressionContextUtils.html). The method you need is QgsExpressionContextUtils.setProjectVariable, e.g.


QgsExpressionContextUtils.setProjectVariable('myvar','hello world')

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...