1

I want to add to the Print Layout Legend groups, subgroups, and layers using PyQGIS like in the picture:

Legend items

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?

1 Answer 1

3

You are just missing a call to get the QgsMapLayer from the QgsLayerTreeLayer which is what QgsLayerTreeGroup.addLayer() expects:

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_.layer())  # CHANGE IS HERE

legend.model().setRootGroup(self.root)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.