I am working on a QGIS plugin in python. In this plugin I load two layers. These layers are polygons which represent administrative boundaries. My plugin load also several print layout in a Qgis project. In these print layout there is a legend. I would like that in the legend of the composer it is displayed only the layers that are visible in the map of the composer. The problem is that my administrative boundaries are represented as a polygon and therefore the layer is always present in my map while the administrative boundaries are not visible in the map if I use the option "Show features only inside the linked map". How can I do not to display the layers of the administrative boundaries in the legend if they are not visible in the extent of the map ? I tried this code.
project = QgsProject.instance()
root = QgsProject.instance().layerTreeRoot()
groupe_admin = root.addGroup("Limites administratives")
dep_layer = QgsVectorLayer('C:/dep.shp', 'DEPARTEMENT', 'ogr')
reg_layer = QgsVectorLayer('C:/reg.shp', 'REGIONS', 'ogr')
QgsProject.instance().addMapLayer(dep_layer, False)
QgsProject.instance().addMapLayer(reg_layer, False)
groupe_admin.addLayer(dep_layer)
groupe_admin.addLayer(reg_layer)
processing.run("qgis:polygonstolines", {'INPUT': dep_layer, 'OUTPUT': 'C:/dep_lignes.shp'})
processing.run("qgis:polygonstolines", {'INPUT': reg_layer, 'OUTPUT': 'C:/reg_lignes.shp'})
depL_layer = QgsVectorLayer('C:/dep_lignes.shp', 'DEP', 'ogr')
regL_layer = QgsVectorLayer('C:/reg_lignes.shp', 'REG', 'ogr')
QgsProject.instance().addMapLayer(depL_layer, False)
QgsProject.instance().addMapLayer(regL_layer, False)
layout = QgsPrintLayout(project)
document = QDomDocument()
template_file = open('C:/Users/Thysma/Documents/Stage/Composeurs/A4 PT.qpt')
template_content = template_file.read()
template_file.close()
document.setContent(template_content)
layout.loadFromTemplate(document, QgsReadWriteContext())
project.layoutManager().addLayout(layout)
map = layout.itemById("map")
processing.run("qgis:extenttolayer", {'INPUT': map.extent(), 'OUTPUT': 'C:/emprise_carte.shp'})
layout_map_layer = QgsVectorLayer('C:/emprise_carte.shp', 'Emprise Carte', 'ogr')
processing.run("qgis:selectbylocation", {'INPUT': depL_layer,
'PREDICATE': 0,
'INTERSECT': layout_map_layer,
'METHOD': 0})
depL_feat = depL_layer.selectedFeatureCount()
if depL_feat == 0:
depL_layer.removeSelection()
depL_feat = 0
legend = [i for i in layout.items() if isinstance(i, QgsLayoutItemLegend)][0]
legend.setAutoUpdateModel(False)
rootGroup_admin =
legend.model().rootGroup().findGroup('Limitesadministratives')
rootGroup_admin.removeLayer(dep_layer)
legend.adjustBoxSize()
layout.refresh()