Geographic Information Systems Asked by Juliette Lapeyre on March 13, 2021
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)
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()
...
Correct answer by Kadir Şahbaz on March 13, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP