I'm writing a standalone application using QGIS API to export maps automatically as pdf.
When I'm building my QgsComposition, I have an issue:
I have already built a list with the layers I want to show on the map (not all the layers from the original project), but my QgsComposerLegend shows all the layers.
First, I tried this:
legend = QgsComposerLegend(c) legend.setTitle(u"Légende:") legend.model().setLayerSet(renderer.layerSet()) [...] c.addComposerLegend(legend)
And the result:
But the layer set is not the one I want.
I found this post: Filter MapComposer legend to only show layers visible on the map
I adapted its code to mine and I have this:
With the code:
legend = QgsComposerLegend(c) legend.setTitle(u"Légende:") layerGroup = QgsLayerTreeGroup() for layer in layers: layerGroup.insertLayer(0, layer) legend.modelV2().setRootGroup(layerGroup) [...] c.addComposerLegend(legend)
The issue is that I would keep the initial tree organization, and just suppress the layers I don't want.
I tried using the QgsLayerTreeGroup methods this way:
legend = QgsComposerLegend(c) legend.setTitle(u"Légende:") layersToRemove =  for layer in legend.modelV2().rootGroup().findLayers(): if layer.layer() not in layers: layersToRemove.append(layer.layer()) for layer in layerToRemove: # print(layer.id()) legend.modelV2().rootGroup().removeLayer(layer) [...] c.addComposerLegend(legend)
But I have the same result as the first code... I don't understand why, but the layers are not removed from the tree... Any idea ?