Is there a way to hide a layer name in the composer legend using pyqgis as we do from the legend properties (see picture)?

enter image description here

The only way I've found so far is by changing the layer name in the composer legend but it will also change it in the Layers list and I don't want that.

This is the code I used:

        itemLlegend = composition.getComposerItemById('Legend')
        modelindex=itemLlegend.modelV2().index(0, 0)

Any idea?

2 Answers 2


I had this problem too. My friend who is working for QGIS told me how.

What you can do is:

take the QgsLayerTreeLayer from the model (if you haven't include it in the model):

tree_layer = itemLlegend.modelV2().rootGroup().addLayer(layer)

If your layer is already in the model, just iterate rootGroup and grab your tree_layer.

After you got your tree layer:

from qgis.core import QgsLegendRenderer, QgsComposerLegendStyle
    tree_layer, QgsComposerLegendStyle.Hidden)

This will add style to your tree_layer it will now will be hidden by the renderer (but, just the Visitors text will be hidden).

  • Can this code change the layer name of the legend?
    – natsuapo
    Commented Mar 16, 2018 at 5:28
  • Yes, but I don't see why you prefer this over changing the layer name directly in the layer.
    – lucernae
    Commented Oct 17, 2019 at 9:34

The updated recipe for QGIS 3.x

from qgis.core import QgsLayoutItemLegend, QgsLegendRenderer, QgsLegendStyle, QgsProject

project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName('print1') # Your layout name

# If only one legend within the layout
layoutItemLegend = [i for i in layout.items() if isinstance(i,  QgsLayoutItemLegend)][0]
# Could also use the following if you defined an id 'mylegend' for the QgsLayoutItemLegend (commented here)
# layoutItemLegend = layout.itemById('mylegend')
model = layoutItemLegend.model()
tree_legend = model.rootGroup()

# Desactivate auto refresh of the legend

# Then do to apply change for the first element (group or layer)
    tree_legend.children()[0], QgsLegendStyle.Hidden)

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.