[GIS] Save vector layer and update .qgs project file (PyQGIS)

pyqgisqgis-pluginsqgs

Need help to solve the following use case:

  1. QGIS started with new project (no layers)
  2. New layer is created programmatically and data is populated:

    vl = QgsVectorLayer("Point", "temporary_points", "memory")
    pr = vl.dataProvider()
    vl.startEditing()     
    <... put data into vl>
    vl.commitChanges()
    QgsMapLayerRegistry.instance().addMapLayer(vl)
    
  3. New layer is saved as shapefile:

    QgsVectorFileWriter.writeAsVectorFormat(vl, "c:\\temp\\my_shapes.shp", "CP1250", None, "ESRI Shapefile")
    
  4. Then I assume I need to update my layer to change data type from "memory" to "ogr" with the path to shapefile from step #3.

  5. Then update project file with this info; so the next time this project is loaded – the layer will read data from my_shapes.shp.

I "kind of" know how to make these #4 and #5 steps using QGIS UI:

  • save layer as shapefile plus set "Add saved layer to map" check box.
  • delete original layer
  • save project

Shall I implement these steps programmatically or there is better way?

Best Answer

Do you need the memory layer at all?

Have a look at the "directly from features" example in the PyQGIS cookbook to see how to create a persistent Shapefile from features, so that you avoid creating a memory layer.

Related Question