In my QGIS plugin I select dynamically features from a Vector layer. and currently i create a new layer (Shapefile) from selection on combining all feature into a new feature:

theField = QgsField
self.theString = (os.path.expanduser("~")+'\.qgis\\statsRectangle.shp')
feat = QgsFeature()
shapeLayer2 = QgsVectorLayer(self.theString, "Upstream Area Of Interest", 'ogr')
geomtotSubwatershed = QgsGeometry.fromWkt('GEOMETRYCOLLECTION EMPTY')
UpstreamGeometry = QgsGeometry.fromWkt('GEOMETRYCOLLECTION EMPTY')
for elem in nodLayer.selectedFeatures():
   UpstreamGeometry= UpstreamGeometry.combine(elem.geometry())

but combining selected feature take a long time and froze QGIS UI.

  • Do you want a memory layer or shp file? – Nathan W Dec 12 '13 at 14:25
  • I want a shape layer – fkili mohamed Dec 12 '13 at 14:31
  • check out qgis.org/api/… (don't have time for a full answer) – Nathan W Dec 12 '13 at 14:39

Old question but I was searching for this today - here is what I did:

layer = iface.activeLayer()
QgsVectorFileWriter.writeAsVectorFormat( layer, 'H:/temp/' + layer.name() + ".shp", "utf-8", layer.crs(), "ESRI Shapefile", 1)

The boolean option '1' at the end of the command results in saving just the selected features of the layer.

  • it asks me again the crs even I describe layer.crs() – Mustafa Uçar Mar 14 '18 at 7:56

In QGIS 3, there is new helper for that:

layer = iface.activeLayer()
new_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.selectedFeatureIds()))

This will give you a memory layer. Then you can still write it to disk if necessary with the QgsVectorFileWriter.

PS, IMHO, you should try to avoid shapefile. People might come with some layers if longer field names and they will be truncated. Especially in QGIS3, GeoPackage is the default format.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.