PyQGIS Legend – Removing Layer from Legend in PyQGIS

pyqgispyqgis-3qgisqgis-print-layouts

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
layout.initializeDefaults()
layout.setName('LayoutWithLegend')

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

itemLegend = QgsLayoutItemLegend.create(layout)

itemLegend.attemptResize(QgsLayoutSize(60, 40, 
QgsUnitTypes.LayoutMillimeters))

layout.addLayoutItem(itemLegend)

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?

Best Answer

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

def rmvLyr(lyrname):
    qinst = QgsProject.instance()
    qinst.removeMapLayer(qinst.mapLayersByName(lyrname)[0].id())

Call it by :

for lyr in ['Patient Data', 'Google Maps']:
    rmvLyr(lyr)
Related Question