[GIS] How to create a new layer from the current selection using PyQGIS

pyqgispythonqgis

Is it possible to create a duplicate layer, only displaying the selection from the layer you are duplicating in QuantumGIS?
Similar to ArcGIS -> Create Layer from Selected Features.

I looked at "How to duplicate a layer"

iface = qgis.utils.iface
vl = iface.activeLayer()
iface.addVectorLayer( vl.source(), vl.name(), vl.providerType() )

but can't see how to duplicate only the selected features?

Best Answer

You can retrieve the selected features with

vl = iface.activeLayer()
selectedFeatures = vl.selectedFeatures()

You then need to add a new vector layer. If you want your duplicate layer only in memory (i.e. not persistent) use a memory layer (see the pyqgis cookbook) If you want your layer to be persistent, refer to the section about writing vector layers.

Use then the QgsVectorFileWriter.addFeature or QgsVectorLayer.addFeatures method on the retrieved layer / layerwriter to add the features.

In case you have really many features, it might be prudent to use selectedFeaturesIds() and then query and iterate over these to not have to copy all the features into the memory.

Related Question