3

In a plugin I want to save the selected features in a new shapefile. I search and I try (How can I create a new layer from the currrent selection? to create a new layer and write the selected fields and features in that:

    vl = QgsVectorLayer("Polygon", "temporary_points", "memory")
    pr = vl.dataProvider()

    # add geometry and fields
    pr.addAttributes(fields)
    pr.addFeatures(features)

But this result is not what I wanted. I get this: enter image description here

In this image, the selected polygon is yellow and the pink polygon is the saved one as another shapefile. So the geometry is not completely correct and I need the perfect copy of the original.

Anyone knows how to get it?


I can use the algorithm from Processing Toolbox, "Save selected features".

5
  • How about the "Save as" option?? You can select your features and then right click, you choose Save as>-Save only selected features.
    – geo_dd
    Commented Nov 16, 2015 at 17:24
  • Yes, I know that but I want in Python code. Commented Nov 16, 2015 at 17:38
  • I get it. Ii can use the algorithm in processing toolbox, "Save selected features". Thanks anyway. I will edit the question. Commented Nov 16, 2015 at 17:39
  • Did you search on GIS SE ? (How can I create a new layer from the currrent selection?, ...)
    – gene
    Commented Nov 16, 2015 at 17:46
  • yes, that's what I did in the first place and get the result presented in image. Commented Nov 17, 2015 at 10:01

1 Answer 1

1

You can save selected features from your active layer into a Shapefile simply calling QgsVectorFileWriter.writeAsVectorFormat and passing the onlySelected parameter as True:

layer = iface.activeLayer()
res = QgsVectorFileWriter.writeAsVectorFormat( layer,
                                               '/tmp/selectedFeatures.shp',
                                               'System',
                                               None, #crs
                                               'ESRI Shapefile',
                                               True #onlySelected
                                             )
if res != QgsVectorFileWriter.NoError:
    print 'Error number:', res
else:
    print "Done!"

The resulting layer will contain all fields from source layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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