PyQGIS – Exporting Filtered Atlas Layout for Print Composer

layoutsprint-composerpyqgis

I have a simple print layout in QGIS with an atlas. I'm defining a simple filter expression (tested and working with the GUI) that is filtering only one single polygon layer.

What I'm trying to do is to export the atlas with pyqgis, but it seems that the setFilterExpression function is not taken into account: it is exporting as many pdf as the feature count.

This is the small script:

manager = QgsProject.instance().layoutManager()

layout = manager.layoutByName("layout")
atlas = layout.atlas()
atlas.setFilterExpression(''' "continent" = 'europe' ''')

atlas.beginRender()

for i in range(0, atlas.count()):
    exporter = QgsLayoutExporter(atlas.layout())
    print(atlas.filterExpression())
    exporter.exportToPdf('destination_folder' + atlas.currentFilename() + ".pdf", QgsLayoutExporter.PdfExportSettings())
    atlas.next()

the script is linked to this other question: PyQGIS control creation Atlas Layout

Best Answer

OK got it. I was missing the setFilterFeatures method. So the updated script is:

manager = QgsProject.instance().layoutManager()

layout = manager.layoutByName("layout")
atlas = layout.atlas()

atlas.setFilterFeatures(True)
atlas.setFilterExpression(''' "continent" = 'europe' ''')

atlas.beginRender()

for i in range(0, atlas.count()):
    exporter = QgsLayoutExporter(atlas.layout())
    print(atlas.filterExpression())
    exporter.exportToPdf('destination_folder' + atlas.currentFilename() + ".pdf", QgsLayoutExporter.PdfExportSettings())
    atlas.next()

atlas.endRender()
Related Question