How to remove legend items with PyQGIS without removing the layer?
This is code adapted for QGIS 3 from this answer. It adds all layers except one specified. You could swap this out for a list, or conversely, use the layers you want to keep in rather than those you want to leave out.
l = QgsProject.instance().layoutManager()
for layout in l.printLayouts():
legend = QgsLayoutItemLegend(layout)
root = QgsLayerTree()
for lyr in iface.mapCanvas().layers():
if lyr.name() != 'Unwanted layer':
root.addLayer(lyr)
legend.model().setRootGroup(root)
layout.addItem(legend)
In place of if lyr.name() != 'Unwanted layer':
you could use
if lyr.name() not in [list, of, unwanted, layer, names]:
or
if lyr.name() in [list, of, wanted, layer, names]:
Matt Needle, your solution started to work after I've forced qt to process the bufferd events, before iterating through layers. Thank you for your hint.
from PyQt5 import QtWidgets
inst = QtWidgets.QApplication.instance()
qapp = QtWidgets.qApp
qapp.processEvents()
l = QgsProject.instance().layoutManager()
for layout in l.printLayouts():
legend = QgsLayoutItemLegend(layout)
root = QgsLayerTree()
for lyr in iface.mapCanvas().layers():
if lyr.name() != 'Unwanted layer':
root.addLayer(lyr)
legend.model().setRootGroup(root)
layout.addItem(legend)