7

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?

Taras
35.7k5 gold badges77 silver badges151 bronze badges
asked Jun 21, 2013 at 14:57

2 Answers 2

9

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 memory.

Taras
35.7k5 gold badges77 silver badges151 bronze badges
answered Jun 21, 2013 at 17:17
1
  • 2
    You can also use "save selection as". First you select the feature(s),then select the layer, right click and choose save selection as. Here you can define the type of file, shape for instance. Works like data export data /selected features in ArcMap Commented Jun 21, 2013 at 18:11
1

Since QGIS 3.0, there is another approach available. Use the materialize() method from the QgsFeatureSource class.

Here, the code will create a new temporary layer from the selection of all features with the selectedFeatureIds() method from the QgsVectorLayer class. The selection can be adjusted accordingly.

# imports
from qgis.utils import iface
from qgis.core import QgsFeatureRequest, QgsProject
# choose a layer
layer = iface.activeLayer()
# or with: layer = QgsProject.instance().mapLayersByName('LAYER_NAME')[0]
# select all features in the original layer
layer.selectAll()
# create a new layer from selected features
new_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.selectedFeatureIds()))
# remove selection in the original layer
layer.removeSelection()
# add a new layer to the map 
QgsProject.instance().addMapLayer(new_layer)

References:

answered Apr 18 at 9:59

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.