12

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')
nodLayer.setSelectedFeatures(selectFeatureIDlist)
UpstreamGeometry = QgsGeometry.fromWkt('GEOMETRYCOLLECTION EMPTY')
for elem in nodLayer.selectedFeatures():
 UpstreamGeometry = UpstreamGeometry.combine(elem.geometry())
feat.setGeometry(UpstreamGeometry)
QgsMapLayerRegistry.instance().addMapLayer(shapeLayer2)

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

Taras
35.7k5 gold badges77 silver badges151 bronze badges
asked Dec 12, 2013 at 14:17
4
  • Do you want a memory layer or shp file? Commented Dec 12, 2013 at 14:25
  • I want a shape layer Commented Dec 12, 2013 at 14:31
  • check out qgis.org/api/… (don't have time for a full answer) Commented Dec 12, 2013 at 14:39
  • Please, do not forget about "What should I do when someone answers my question?" Commented Apr 25, 2022 at 11:07

2 Answers 2

18

In QGIS 3, there is new helper for that:

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

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.

answered Nov 20, 2017 at 11:08
1
  • 2
    It is really cool! Commented Feb 15, 2018 at 7:21
12

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.

answered Jun 30, 2016 at 13:49
1
  • it asks me again the crs even I describe layer.crs() Commented Mar 14, 2018 at 7:56

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.