Search code examples
variablesqgis

QGIS add project variables using python code


Is it possible to create/update project variables in QGIS through code? We generate about 1000 small projects a year in my company - for each job, we copy a QGIS template. Our goal is to use project variables within the QGIS project - but we'd like to pre-populate them when we copy the template. Alternatively - if we stored all of our QGIS projects in Postgres, could we store/retrieve the project variables in the database? A project table, for instance?


Solution

  • ProjectInstance = QgsProject.instance()
    
    #Use this to set the Variable
    QgsExpressionContextUtils.setProjectVariable(ProjectInstance, 'myVariable','myValue')
    
    #Use this to get the Variable
    print(QgsExpressionContextUtils.projectScope(ProjectInstance).variable('myVariable'))