PyQGIS – How to Add Variable to Print Layout using QGIS

print-composerpyqgisqgis-3qgis-variable

I have a QGIS workspace (3.26) containing several vector and raster datasets. I plan to produce multiple print layouts from this workspace to display information such as the site location, predicted flood extents, LiDAR levels, etc. on separate maps.

I am in the process of writing a short python script and UI to help users specify variables at the project level such as a project name/number and a client name. These values will then inform all print layouts. I'm using code similar to the snippet below to achieve this:

QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(), 'clientName','Dave')

These project level variables work for values that do not change between print layouts such as the client name, but I'm looking to add some more variables at the print layout level – e.g. plot name. Is there a print layout equivalent to the code above to set a variable to a map rather than the project?

Best Answer

There is the function QgsExpressionContextUtils.setLayoutVariable which takes a QgsLayout as a first parameter, maybe that would be what you can use?

Documentation is at https://qgis.org/pyqgis/3.26/core/QgsExpressionContextUtils.html#qgis.core.QgsExpressionContextUtils.setLayoutVariable

Related Question