QGIS Automation – Export Layouts by Looping on Project Layers

layoutsprint-composerpyqgisqgis

I've a QGIS project with several vector layers that I need to be represented in a layout I've prepared one by one.

I can manually make visible and select one layer at a time, so that the layout after a refresh shows the desired layer map and legend (where I've selected only show items in the selected map in the interface).
I'm able to select layers by name, and also 'activate' them, but I'm not finding a way to set visibility and active in a PyQGIS script for the layers one by one to automate the export of the layers maps with the layout.

Best Answer

There is a solution to roll on layer you use in your qgis project.

It is based on a mix between this answer and this answer.

The goal is to bend the atlas function to roll to the layer you have in your project.

  1. set the name of the layers to be all different.
  2. create a layer that is named atlas as non geographic layer with no attribute. Then create as many features in this layer as there is layer in your project.
  3. open a layout, then add your map frame. Then activate atlas and use the layer created before as atlas coverage. Then in the map propreties > Layers set the layers to be locked and to be data driven.

enter image description here

  1. Then an expression helper pops out. Set it to give the name of each layer in your project based on the atlas number. This formula may work well :
layer_property(array_get(@layers, @atlas_featurenumber -1) , 'name')
  1. Then you may set the name of the atlas page or anything else and export the atlas.
Related Question