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)

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:


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

  • Still in need of help in this one.
    – Farhan
    Commented Oct 24, 2018 at 7:58

1 Answer 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)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.