I work on QGIS Plugin in python. This plugin load several Print layout in a QGIS project. These print layout contain a legend. I would like to be able to remove a layer from the composer legend without this layer being deleted in the main map. For that I found the code of Ben W on GIS Stack Exchange Hide legend entries in PyQGIS and it works very well. But in my case the layers are organized in groups like in the photo below. When I use groups the code doesn't work anymore. There is no error but the layer is not deleted from the legend. How could I arrange this code to work with layers that are in groups ?
Code of Ben W that I tried:
project = QgsProject().instance()
layer_to_remove = project.mapLayersByName('Your Layer Name')[0]
layout = project.layoutManager().layoutByName('Your Layout Name')
legend = [i for i in layout.items() if isinstance(i, QgsLayoutItemLegend)][0]
legend.setAutoUpdateModel(False)
legend.model().rootGroup().removeLayer(layer_to_remove)
legend.adjustBoxSize()
layout.refresh()
Organisation of my layers: