TransWikia.com

Renaming multiple layers in the legend from an attribute in each layer in QGIS

Geographic Information Systems Asked by WestCorkPalaeo on May 30, 2021

I have 72 layers that have been generated via affine transform of a single layer that has 72 categories. But the 72 layers have been given names that are sequential numeric. The original categories are named by a field UNIT_NAME. I want the 72 generated layers to have this attribute as a layer name for each of them.

Can I get affine transform function to name the generated layers using the value from the UNIT_NAME attribute of each layer; or can I rename all the layers to have this value, in a script?

I am using QGIS 3.16.1 Hannover on Windows 7.

2 Answers

You can use a script like this:

layers = QgsProject.instance().mapLayers().values()

for layer in layers:
    # get the first feature's UNIT_NAME value
    name = layer.getFeature(0)["UNIT_NAME"]
    layer.setName(name)

Note: The script changes the name of the single layer that has 72 categories, too, if it exists in Layers panel. So you can add an if statement to pass that layer.

layers = QgsProject.instance().mapLayers().values()

for layer in layers:
    if layer.name() == "NAME_OF_THE_SINGLE_LAYER":
        continue

    name = layer.getFeature(0)["UNIT_NAME"]
    layer.setName(name)

Correct answer by Kadir Şahbaz on May 30, 2021

So extending Kadir's answer, because I did not want all layers to be renamed, just those that got assigned names with a specific string through affine transform, I came up with the following, which worked nicely.

import re
RES_STRING='Palinspastic'
STRING=re.compile(RES_STRING)
layers = QgsProject.instance().mapLayers().values()
for layer in layers:
    LAYER_NAME=layer.name()
    if STRING.search(LAYER_NAME):
        name = layer.getFeature(0)["UNIT_NAME"]
        layer.setName(name)

Answered by WestCorkPalaeo on May 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP