12

I can change user defined project variables by QgsExpressionContextUtils.setProjectVariable('myvar','hello world')

But how can I access/read this variable in a python script?

ahmadhanb
  • 40,826
  • 5
  • 51
  • 105
Karel DG
  • 121
  • 4
  • 1
    I cannot try this but documentation suggests that there should be a QgsExpressionContextUtils.projectScope method through which you can access that information. – Christoph Dec 24 '16 at 08:23

2 Answers2

20

Since QGIS 3.0 you need also to specify the project when setting and reading a variable:

project = QgsProject.instance()
QgsExpressionContextUtils.setProjectVariable(project,'myvar','Hello World!')
QgsExpressionContextUtils.projectScope(project).variable('myvar')
srjskam
  • 371
  • 2
  • 2
6

If you set a project variable using:

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

You can use the following to read the value of this variable:

QgsExpressionContextUtils.projectScope().variable('myvar')
>>> u'hello world'
Joseph
  • 75,746
  • 7
  • 171
  • 282