TransWikia.com

PyQGIS: QgsVectorFileWriter.create() doesn't flush even after deleted

Geographic Information Systems Asked by user159687 on November 4, 2020

If QgsVectorFileWriter constructor is directly used, the output is flushed when the reference is deleted. I’m trying to switch to QgsVectorFileWriter.create() because QGIS warns that the former is being deprecated. But as far as I tested, QgsVectorFileWriter.create() does not flush the output until QgsApplication.exitQgis() is called.

I’m not familiar with Python, QGIS, and C++. I see that QgsVectorFileWriterTask does something asynchronous, but I’m so weak to follow the code.

QGIS version: 3.10.3
OS: macOS 10.15.3

2 Answers

QgsVectorFileWriter.create() does not flush the output until QgsApplication.exitQgis() is called, because create() method uses QgsVectorFileWriter constructor method behind the scenes.Since it's deleted while exiting QGIS, it flushes the output.

Use newly added writeAsVectorFormatV2 method.

layer = iface.activeLayer()
file_path = "/Path/To/File.shp"

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "ESRI Shapefile"

QgsVectorFileWriter.writeAsVectorFormatV2(layer, file_path, QgsCoordinateTransformContext(), options)

Answered by Kadir Şahbaz on November 4, 2020

It seems to be a bug that might be fixed in next release (3.16): https://github.com/qgis/QGIS/issues/37629

You can work around it by creating the file with QgsVectorFileWriter and then open the file and add the attributes and features again, somewhat like:

fields = src_layer.fields()

layer = iface.addVectorLayer(layer_path, layer_name , "ogr")
pr = layer.dataProvider()
pr.addAttributes(fields)
layer.updateFields()

fs = []
for src_f in src_layer.getFeatures():
    f = QgsFeature(src_f)
    f.setAttributes(src_f.attributes())
    f.setGeometry(some_kind_of_geom)
    fs.append(f)

pr.addFeatures(fs)

Answered by Pepijn on November 4, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP