3

I have seen Duplicating layer in memory using pyqgis? and I would like to do the same but for any active layer in the TOC whether it is a Polygon, Linestring or Point layer.

Is it possible?

This is the code I tried

 iface = qgis.utils.iface 
vl = iface.activeLayer() 
feats = [feat for feat in vl.getFeatures()] 
mem_layer = QgsVectorLayer(vl.source(), "duplicated_layer", "memory") mem_layer_data = mem_layer.dataProvider() 
attr = layer.dataProvider().fields().toList() mem_layer_data.addAttributes(attr) mem_layer.updateFields() mem_layer_data.addFeatures(feats) QgsMapLayerRegistry.instance().addMapLayer(mem_layer)
3
  • What does your attempt to write this code look like? Commented Jan 23, 2017 at 12:56
  • I looks like this: Commented Jan 23, 2017 at 13:59
  • 1
    Thanks for the support, I tried to edit, I hope it is ok. Commented Jan 24, 2017 at 9:14

2 Answers 2

2

Try using the following in the Python Console which should do the following:

  • Determines layer type (e.g. point, linestring or polygon).
  • Creates a duplicated layer containing a copy of all features and attributes.
  • Assigns a CRS (Coordinate Reference System) which you specify when running the function.

Here is the code:

def dup_layer(crs):
 layer = iface.activeLayer()
 layer_type = {'0':'Point', '1':'LineString', '2':'Polygon'}
 mem_layer = QgsVectorLayer(layer_type[str(layer.geometryType())] + "?crs=epsg:" + str(crs), "duplicated_layer", "memory")
 feats = [feat for feat in layer.getFeatures()]
 mem_layer_data = mem_layer.dataProvider()
 attr = layer.dataProvider().fields().toList()
 mem_layer_data.addAttributes(attr)
 mem_layer.updateFields()
 mem_layer_data.addFeatures(feats)
 QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

After you type the code into the console, select a layer and type the following:

dup_layer(4326)

This will create a duplicated layer with a CRS of EPSG:4326. You change the CRS to fit your needs.

answered Jan 24, 2017 at 12:36
1
  • @E.Salas - Most welcome, glad it worked :) Commented Jan 25, 2017 at 9:51
0

The question you referenced has a new answer now that should do what you need (and with considerably less code):

layer.selectAll()
clone_layer = processing.run("native:saveselectedfeatures", {'INPUT': layer, 'OUTPUT': 'memory:'})['OUTPUT']

To deselect everything afterwards you can use:

layer.removeSelection()
answered Apr 6, 2020 at 5:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.