4

I have developed a custom qgis plugin. I have a button to export the map canvas in the form of image along with the legend. I came up with the following code for the legend:

    legend = QgsComposerLegend(c)
    legend.model().setLayerSet(mapRenderer.layerSet())
    c.addItem(legend)

The problem is that it adds all the features in the map legend whereas I only want to include the selected features in the map legend. I also tried:

    legend.setLegendFilterByMapEnabled(True)

But this does not seem to work. Any ideas on how to solve this issue?

TomazicM
  • 25,601
  • 22
  • 29
  • 39
Farhan
  • 127
  • 2
  • 14

1 Answers1

1

If I've correctly understood you want to include only layers that intersect the map canvas extent. This is a snippet for doing it:

import qgis.utils

newcomp = iface.createNewComposer()
c = newcomp.composition()

canvas = qgis.utils.iface.mapCanvas()
layers = qgis.utils.iface.legendInterface().layers()
layerGroup = QgsLayerTreeGroup()
for layer in layers:
    if canvas.extent().intersects(layer.extent()):
        layerGroup.insertLayer(0, layer)

legend = QgsComposerLegend(c)
legend.modelV2().setRootGroup(layerGroup)
c.addItem(legend)

This solution is based on information derived from this question and this.

francesco lc
  • 105
  • 5