I am trying to delete a variable from QGIS Project variables. I didn't find the functionality in QgsExpressionContextUtils (I use it to set a variable). I also tried to do this:

project_context_scope = QgsExpressionContextUtils.projectScope()

It does remove from project_context_scope. But, when I open the QGIS Project properties to see the list of variables, the deleted variable is still exist.

May be I was wrong in getting the instance of project_context_scope, since it's not a singleton and projectScope create new object.

  • Did you try with del variable_name? If you have a list: for var in list:...del var. – xunilk Jul 24 '17 at 17:40
  • I don't think that will work since the variable_name is a string. It's like value mapping. – ismailsunni Jul 25 '17 at 1:07

I have found a way to do it, after got suggestion from nwadson's comment

The idea is using QgsExpressionContextUtils.projectScope().variableNames() to get existing variables. Then iterate which variable that you want to keep. After that, you set it with:


Note: there is no high level API to delete a project variable for now.

| improve this answer | |
  • Don't forget to accept your answer by clicking the green-faded tick on the left-hand side :) – Joseph Nov 30 '17 at 12:06

I'm not sure about your use case, but one option is since the .qgs file is just xml you could open the file with python and do a simple .replace then save out each line to a new .qgs file, delete old .qgs file, and rename new back to old .qgs filename.

| improve this answer | |
  • Thanks for the answer. But, for my use case, it won't work since the QGIS project is on the fly. – ismailsunni Jul 26 '17 at 1:02
  • @ismailsunni, can you expand more what you mean by "it won't work since the QGIS project is on the fly"? – artwork21 Jul 26 '17 at 11:55
  • Ah sorry for not so clear reply. So, in my use case, I do not work with the qgs file, but more in the project variable when we run QGIS. I am not sure, but if we updated the .qgs file, we should reload / refresh the project in QGIS. In my case, I can't do that (or may be it's too complicated) – ismailsunni Jul 26 '17 at 15:57

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.