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:


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


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

QgsExpressionContextUtils.setProjectVariable('myvar','hello world')
  • What about deleting a variable? I didn't find method for it in QgsExpressionContextUtils – ismailsunni Jul 24 '17 at 15:39
  • There's no high level API to do this. Possibly you could get away with NULLING the variable (setting it to None), but if not, you need to use QgsExpressionContextUtils.setProjectVariables({} ) and reset the whole lot. You'd first need to check QgsExpressionContextUtils.projectScope() and create a dict of all the variables you want to keep. It's far from ideal - but would also be a trivial addition to the API if you wanted to get involved in QGIS development and send through a pull request on github... – ndawson Jul 24 '17 at 22:58
  • Thanks @ndawson, it works with your work around to reset with setProjectVariables(preserved_variables) I have checked the C++ code, I hope I can contribute for the functionality. – ismailsunni Jul 25 '17 at 2:06
  • QgsExpressionContextUtils.removeProjectVariable exists now! – letmaik Jan 20 '18 at 23:21
  • 1
    There is a new required parameter since QGIS 3.0. See an updated answer here: gis.stackexchange.com/questions/222494/… – TimD Jun 26 '20 at 3:57

In QGIS3, the API needs to pass QgsProject as the first argument.

It is: setProjectVariable(project: QgsProject, name: str, value: Any)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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