I'm working with PyQGIS in QGIS 3.10. I'm trying to remove a layer from the composer legend if it is a raster (but I want to see the raster on the map). This is my code:
for i in self.newLayout.items(): if isinstance(i,QgsLayoutItemLegend): legend = i legend.setAutoUpdateModel(True) for j in range(legend.model().rowCount()): modelindex=legend.model().index(j, 0) layertreenode=legend.model().index2node(modelindex) if layertreenode != QgsLayerTreeGroup : if layertreenode.layer().type()==QgsMapLayer.RasterLayer: layertreenode.setItemVisibilityChecked (False) legend.setAutoUpdateModel(False) legend.setLegendFilterByMapEnabled(True)
It works... but a bit too much: my raster is not anymore visible in the legend, but the layer is set as invisible too (in the composer map and in the canvas)!
I thought I worked only in the legend model! May be I should have used another method like "removeFromLegend"? But I didn't find this anywhere.
More broadly, I think I have difficulties to understand boundaries between layer trees in the table of content and in then composer legend.
EDIT : I read this thread : Remove legend nodes of a categorized layer in a layout legend using PyQgis an tried
if layertreenode.layer().type()==QgsMapLayer.RasterLayer: legend.model().removeRows(j,1)
It removes the legend item, but il also removes completely the raster from the QGIS project.