I want to add to the Print Layout Legend groups, subgroups, and layers using PyQGIS like in the picture:
But I can only add layers:
root = QgsLayerTree()
layers_ = self.qgis_project.mapLayers().values()
for layer_ in layers_:
if layer_.type() == QgsMapLayer.VectorLayer:
if len(list(layer_.getFeatures())) != 0:
self.root.addLayer(layer_)
legend.model().setRootGroup(self.root)
I tried to create a group and add the group to the model:
root = QgsLayerTree()
root_group = QgsProject.instance().layerTreeRoot()
group = root_group.findGroup("Group")
subgroup1 = group.findGroup("Subgroup1")
root.addGroup("Subgroup1")
for layer_ in subgroup1.children():
root.addLayer(layer_)
legend.model().setRootGroup(self.root)
But I get an error:
TypeError: QgsLayerTreeGroup.addLayer(): argument 1 has unexpected type 'QgsLayerTreeLayer'
How can I create Legend Items like in the picture with groups, subgroups, and layers?