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.

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

3 Answers 3

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)

1
  • Don't forget to accept your answer by clicking the green-faded tick on the left-hand side :) Commented Nov 30, 2017 at 12:06
1

In QGIS 3 this functionality is added, simply use:

QgsExpressionContextUtils.removeProjectVariable(QgsProject.instance(), 'your_project_variable_name')
1
  • 1
    ah yes, I ended up implementing the API. Thanks for reminding me. Commented Aug 11, 2023 at 3:11
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.

3
  • Thanks for the answer. But, for my use case, it won't work since the QGIS project is on the fly. Commented Jul 26, 2017 at 1:02
  • @ismailsunni, can you expand more what you mean by "it won't work since the QGIS project is on the fly"? Commented Jul 26, 2017 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) Commented Jul 26, 2017 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.