2

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?

2

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)
  • I think this function will also remove the layer in the project. – natsuapo Jun 10 at 5:56
1

You can try this:

for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() == "Patient Data":
        QgsMapLayerRegistry.instance().removeMapLayers([lyr.id()])

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.