0

I made a template that allows to quickly export a map. For layers groups, i can disabling showing it on legend and symbol stay displayed on the map :
QgsLegendRenderer.setNodeLegendStyle(group, QgsLegendStyle.Hidden)

I would like to make the same for layers but it doesn't work. The legend entry is always visible. The check option "hidden" is well checked in QGIS Composer (bug ?). I've try an other approach with the legend model and i remove the current node :

child = ...
model = legend.model()
index = model.node2index(child)
model.removeRow(index.row(), index.parent())

However, the layer is removed from the main ToC.

Is there a solution to keep the layer in the main ToC and remove the entry (but not the symbol) in a layout in PyQGIS ?

1

Try the approach below. The important line is: legend.setAutoUpdateModel(False). This will remove the legend entry in the layout legend but keep it in the main TOC. Just change the layer and layout names to match yours.

project = QgsProject().instance()
layer_to_remove = project.mapLayersByName('Your Layer Name')[0]
layout = project.layoutManager().layoutByName('Your Layout Name')
legend = [i for i in layout.items() if isinstance(i, QgsLayoutItemLegend)][0]
legend.setAutoUpdateModel(False)
legend.model().rootGroup().removeLayer(layer_to_remove)
legend.adjustBoxSize()
layout.refresh()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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