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 
        for j in range(legend.model().rowCount()):
            modelindex=legend.model().index(j, 0)
            if layertreenode != QgsLayerTreeGroup :
                if layertreenode.layer().type()==QgsMapLayer.RasterLayer:
                    layertreenode.setItemVisibilityChecked (False)

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:

It removes the legend item, but il also removes completely the raster from the QGIS project.

  • What you are looking for is QgsLegendStyle.Hidden (qgis.org/pyqgis/3.0/core/Legend/QgsLegendStyle.html) – Nil Nov 27 '20 at 11:40
  • Thank you very much Nil for your answer. I was able to use QgsLegendStyle.Hidden on my legend items (il it is a raster). Unfortunately, this hide the layer name only, and now a blue square appears to represent the raster. – V Damoy Dec 1 '20 at 7:25
  • After you use QgsLegendStyle.Hidden, did you use the layoutItemLegend.updateLegend() and layout.refresh()? – Nil Dec 1 '20 at 7:43
  • Yes, I use legend.updateLegend() , legend.setAutoUpdateModel(False), legend.setLegendFilterByMapEnabled(True) and self.newLayout.refresh(). Nota : The blue square is not immediately displayed : there's an empty space instead. It becomes visible when I try to change the legend height. – V Damoy Dec 2 '20 at 15:35
  • I found a workaround here : gis.stackexchange.com/questions/306389/… Instead of use autoUpdate Model, you put in the legend layers that you want (and you leave besides the ones you don't want). It should work, but I guess there must be a pyQgis method to do the same as the "minus" button under the legend items list in the parameters! – V Damoy Dec 2 '20 at 15:57

Your Answer

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

Browse other questions tagged or ask your own question.