4

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()
project_context_scope.removeVariable('test')

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.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
ismailsunni
  • 217
  • 1
  • 9

3 Answers3

2

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:

QgsExpressionContextUtils.setProjectVariables(existing_variables)

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

Update: I have implemented the API to do it (like @martin mentioned on the other answer)

ismailsunni
  • 217
  • 1
  • 9
  • 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
1

In QGIS 3 this functionality is added, simply use:

QgsExpressionContextUtils.removeProjectVariable(QgsProject.instance(), 'your_project_variable_name')
Martin
  • 51
  • 4
0

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.

artwork21
  • 35,114
  • 8
  • 66
  • 134
  • 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 01: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