4

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.

5
  • Are you sure you used affine transformation? – Erik Jan 7 at 14:24
  • How the layers panel and UNIT_NAME attribute look like? For features in one layer, they have the same UNIT_NAME value? – Kadir Şahbaz Jan 7 at 14:29
  • Erik. I am sure. – WestCorkPalaeo Jan 7 at 16:00
  • Kadir - The UNIT_NAME is different for every category - there are 72 different categories with unique UNIT_NAMEs – WestCorkPalaeo Jan 7 at 16:01
  • 1
    @Erik - I have to apologise to you - I was convinced it was affine transform, but it wasn't - it was split vector layer I used. Thanks for spotting my error. – WestCorkPalaeo Jan 30 at 22:39
7

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)
2
  • And be sure all layers have UNIT_NAME field. Otherwise you get an error. – Kadir Şahbaz Jan 7 at 14:43
  • Thanks Kadir, that worked perfectly. I shall keep that script for future reference. I shall try modifying the if statement in the second script to pick out all layers with name starting "xxxx" – WestCorkPalaeo Jan 7 at 16:11
4

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)

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.