I'm trying to write python script in QGIS to merge layers having the same name.
To do that I specify the name of layer in the script, so all layers having this name, will be merged. However, since I have a lot of names this is not practical. I tried to convert the names type from unicode to list to be able to iterate in the list of names.
In this script, I specify layer name. I want to iterate over all names and compare them to finally merge layers having same name.
import qgis.core
import processing
def __init__(self, iface):
self.iface = iface
lyr_list=[]
count=1
layers=iface.mapCanvas().layers()
for i in layers:
if i.name() == 'layer_name':
lyr_list.append(i)
processing.runandload("qgis:mergevectorlayers", lyr_list, "memory:merged")
-
please share your script, so we can answer your question more precisely!Riccardo– Riccardo2019年09月13日 11:28:52 +00:00Commented Sep 13, 2019 at 11:28
-
Have you tried to create a dictionary where the key is the layername, and the value is a list of all the layers that have that name? Once you have a dictionary populated you should be able to runandload once for each key in the dictionary.Kirk Kuykendall– Kirk Kuykendall2019年09月13日 20:37:33 +00:00Commented Sep 13, 2019 at 20:37
-
Thanks@Kirk Kuykendall for your response. How can I create this dictionary in python?nermiiine– nermiiine2019年09月14日 15:49:21 +00:00Commented Sep 14, 2019 at 15:49
-
@nermiiine In my answer you have an example of this parameters dictionary.xunilk– xunilk2019年09月19日 20:00:50 +00:00Commented Sep 19, 2019 at 20:00
1 Answer 1
Following code has an example of parameters dictionary and, I modified some little thing in your code because you are tagged this question with qgis-3 and 'runandload' doesn't exist as processing method in pyqgis3. I also modified 'layer_name' for working with my own layers.
import qgis.core
import processing
def __init__(self, iface):
self.iface = iface
lyr_list=[]
count=1
layers=iface.mapCanvas().layers()
for i in layers:
if i.name() == 'polygon1':
lyr_list.append(i)
processing.runAndLoadResults("qgis:mergevectorlayers",
{'LAYERS': lyr_list,
'OUTPUT': "memory:merged"})
So, I loaded same layer twice in Map Canvas of QGIS 3 and, I ran above script in Python Console.
Result (layer Merged) can be observed in following image with attributes table. It worked.
-
Thank you @xunilk for your answer, just I don't want to specify the layer name in the code. So I tried to create a combobox which display layers name. It work fine. If you have any other suggestions will be very helpfulnermiiine– nermiiine2019年09月20日 18:03:25 +00:00Commented Sep 20, 2019 at 18:03