Tuesday, 18 December 2018

How can I duplicate a layer in QGIS?


I'd like to display the same vector data in different ways as different layers. While it's very handy to be able to copy and paste the layer style in 1.8+, it would be nice to be able to select a layer and right-click to copy or duplicate it directly.


Any easy way of doing this, like a Python command?




Update: @dakcarto's suggestion works perfectly. Since I needed to add many duplicate layers, I adapted it to loop as many times as needed:



for n in range(1,5): 
iface = qgis.utils.iface; vl = iface.activeLayer(); iface.addVectorLayer(vl.source(), vl.name() + "_clone" + str(n), vl.providerType())

The only problem is that the new layer becomes the activeLayer, so it adds "_clone" and the number to the previous name, ending up with example_clone1, example_clone1_clone2, up to the unwieldy example_clone1_clone2_clone3_clone4_clone5. Need to figure out how to duplicate from the originally selected layer, now.



Answer



There are two feature requests regarding this (#5899 and #1483). This is certainly a doable feature, and could likely be included in version 2.0, if a developer were interested in adding it; or, a Python plugin developer gave it some consideration.


The #5899 issue also includes some Python code for duplicating a layer (submitted by developer Giuseppe Sucameli):



In the meantime, select the vector layer then open the QGis python console and run:




iface = qgis.utils.iface; vl = iface.activeLayer(); iface.addVectorLayer(vl.source(), vl.name() + "_clone", vl.providerType())


The previous code adds to the map the same sublayer.


It's difficult to do it using a one-line python script like the previous one, but if you know the sublayer name you can just replace vl.source() with vl.source().split("|")[0] + "|layername=my_sublayer_name" where my_sublayer_name is the name of your sublayer.



It appears after running the duplication code, you will have to copy/paste the original layer's style.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...