[GIS] Why does the PyQGIS code for saving selected features result in altered geometries

pyqgisqgis

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

Best Answer

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.