I'm creating a simple print layout with Python. I've created a legend but I want to remove a few items from it.

Here is my code to create a blank Print Layout called "LayoutWithLegend" and add a legend to it:

from qgis.core import *

projectInstance = QgsProject.instance()     #creates a project instance
manager = projectInstance.layoutManager()

layout = QgsPrintLayout(projectInstance)    #needs a QgsProject instance as an argument

manager.addLayout(layout)                   #add layout to manager. layout is a project instance

itemLegend = QgsLayoutItemLegend.create(layout)

itemLegend.attemptResize(QgsLayoutSize(60, 40, 


When created, my legend looks like this : enter image description here

I want to remove the 'Patient Data' and 'Google Maps' basemap from the legend. I can't figure it out but some of my best efforts to try are:

-Looking through QgsLayoutItemLegend methods but none of those appear to be relevant

-Playing with QgsLayerTreeGroup. This class has a removeLayer() method.

Any help?


I think this function will work (for QGIS version >= 3.0) :

def rmvLyr(lyrname):
    qinst = QgsProject.instance()

Call it by :

for lyr in ['Patient Data', 'Google Maps']:
| improve this answer | |
  • I think this function will also remove the layer in the project. – natsuapo Jun 10 '19 at 5:56

You can try this:

for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() == "Patient Data":
| improve this answer | |

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.