Geographic Information Systems Asked by firefly-orange on March 5, 2021
I’m developing a PyQGIS processing script to automatically load some WMS layers and export them as part of a pdf map. I import the layout template from a file, which has the QgsLayoutItemLegend
already created and then add the layers I want to show in the legend. Whilst the layers load correctly and are properly rendered on the QgsLayoutItemMap
in the exported pdf, the WMS legend graphic is missing.
The legend does include the WMS layer name (circled blue in the below image), just not the graphic itself. The pdf map also includes a vector layer which is correctly shown in the legend (circled red).
I’ve replicated this behaviour when manually entering the layers to the layout’s legend item in Print Composer. However, when I adjust the size of the legend, the WMS legend graphic then appears. I tried doing this with PyQGIS in the script as a bit of a hack, but it didn’t work. I’ve also tried legend.updateLegend() and legend.refresh() but no luck.
Below is a code snippet of what I’m doing…
#read layout template
layoutFile = open('layout_path')
layoutContent = layoutFile.read()
layoutFile.close()
document = QDomDocument()
document.setContent(layoutContent)
currentProject = context.project()
layout = core.QgsPrintLayout(currentProject)
layout.initializeDefaults()
layout.loadFromTemplate(document, core.QgsReadWriteContext(), False)
#get legend object and add layers to it
legend = layout.itemById(legend_id)
legendModel = legend.model()
legendRootGroup = legendModel.rootGroup()
legendRootGroup.clear()
for l in layers_to_show: #a list of QgsVectorLayers and QgsRasterLayers
legendRootGroup.addLayer(l)
legend.refresh()
legend.updateLegend()
#export pdf
exporter = core.QgsLayoutExporter(layout)
exporter.exportToPdf(saveAs, core.QgsLayoutExporter.PdfExportSettings())
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP