3

The script below is to merge number of layers in a specific group, the output layer name is Merged. How can I change the name? I tried to change the output parameters but it's not working.

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("RL")
layers = [layer.layer()
for layer in group.children()] 
merged = processing.run("native:mergevectorlayers",\
{'LAYERS': layers, 'OUTPUT':"TEMPORARY_OUTPUT"})["OUTPUT"]
QgsProject.instance().addMapLayer(merged, False)
root.insertLayer(0, merged)

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("SL")
layers = [layer.layer()
for layer in group.children()]
merged = processing.run("native:mergevectorlayers",\
{'LAYERS': layers, 'OUTPUT':"TEMPORARY_OUTPUT"})["OUTPUT"]
QgsProject.instance().addMapLayer(merged, False)
root.insertLayer(0, merged)
1
  • 1
    Just a tip, you don't need to use line endings ; with Python
    – Matt
    Commented Jan 23, 2022 at 12:11

2 Answers 2

5

You can use the QgsMapLayer.setName() function. Based on your script, you can do something along the lines of:

merged.setName("This is the new layer name")
4
  • I write it at the end of the script but it gives me error Commented Jan 23, 2022 at 11:02
  • What is the error message? Otherwise, I would suggest to put the command right after you have executed the processing algorithm (i.e., before calling addMapLayer())
    – fastest
    Commented Jan 23, 2022 at 11:05
  • what is the error? it works.
    – Jacqueline
    Commented Jan 23, 2022 at 16:39
  • I tried this and it's working ``` blockLayer = QgsProject.instance().mapLayersByName("Merged")[0] blockLayer.setName("SL Dozers") Commented Jan 23, 2022 at 16:54
2

In a comment you said "I tried this and it's working"

blockLayer = QgsProject.instance().mapLayersByName("Merged")[0] 
blockLayer.setName("SL Dozers")

This may not work if there should be more than one layer with the same name in your project. See my answer to a similar question for a failsafe way: https://gis.stackexchange.com/a/352267/10123

output = processing.run("native:mergevectorlayers",\
{'LAYERS': layers, 'OUTPUT':"TEMPORARY_OUTPUT"})["OUTPUT"]
createdlayer = QgsProject.instance().mapLayer(output)
createdlayer.setName('My shiny new beautiful layer') 

(Explanation: What is returned by the algorithm is a dictionary where you can find an id for the layer, then you can get and rename the layer using the unique id rather than the name)

2
  • there is an error with "parmas" in the first line you typed Commented Jan 23, 2022 at 20:17
  • That is just whatever parameters you put onto the function, I rewrote it to use your example, hope this works Commented Jan 23, 2022 at 21:00

Your Answer

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

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