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?
2 Answers 2
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.
-
2You 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 ArcMapGerardo Jimenez– Gerardo Jimenez2013年06月21日 18:11:47 +00:00Commented Jun 21, 2013 at 18:11
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:
Explore related questions
See similar questions with these tags.