Python QGIS – How to Change a Project Variable Using PyQGIS

pyqgisqgis

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 …

Best Answer

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

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