8

I would like to update the legend item in my layout with other names.

I tried the following code, which returns no error but layers name remain the same.

project = QgsProject.instance()
layout = QgsPrintLayout(project)
layout.initializeDefaults()

layersToAdd = [puit, puit_m, amas, home, fosse, eau_l, eau_p, pdf] # each layer is defined with mapLayersByName
Names = ['Puit', 'Puit municipal', 'Amas', 'Maison', 'Fossé', 'Cours d\'eau', 'Surface d\'eau', 'Champs']
legend = QgsLayoutItemLegend(layout)
legend.setAutoUpdateModel(False)
root = QgsLayerTree()
tree=legend.model().rootGroup()
i = 0
for layer in layersToAdd:
    #add layer objects to the layer tree
    root.addLayer(layer)
    tree.children()[i].setName(Names[i])
    i += 1
legend.updateLegend()
legend.model().setRootGroup(root)
layout.addLayoutItem(legend)

10

You must set setUseLayerName() to False to name legend tree layers manually.

#
# previous lines
#

for i, layer in enumerate(layersToAdd):
    tree_layer = root.addLayer(layer)
    tree_layer.setUseLayerName(False)
    tree_layer.setName(names[i])
    
legend.updateLegend()

...
1
  • Perfect, thank you for the quick answer ! I didn't see this method Jan 21 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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