1

I want to export the PostGIS layer as a shapefile. I need to use replace all selected raw field values with displayed values in QGIS. To do so, I follow PyQGIS Export table with Replace all selected raw field values by displayed values option. But my QGIS crashed.

I found the problem in this line (options.fieldValueConverter = QgsVectorFileWriter.FieldValueConverter()). I do not know what is the reason for this crashing.

This is my complete code.

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = 'GPKG'
options.fileEncoding = 'utf-8'
options.fieldValueConverter = QgsVectorFileWriter.FieldValueConverter()
QgsVectorFileWriter.writeAsVectorFormat(layer, output_file_name, options)

Can anyone help me what is the problem?

1

1 Answer 1

1

Simple as possible

You need to provide an implementation of QgsVectorFileWriter.FieldValueConverter.

This is better explained in Problem with export vector layer by PyQGIS in QGIS. Check the implementation posted there, to get an improved class to transform the field values according to the editor settings.

With a a very basic implementation, like the following, QGIS will not crash.

class CustomFieldValueConverter(QgsVectorFileWriter.FieldValueConverter):

    def __init__(self, layer):
        QgsVectorFileWriter.FieldValueConverter.__init__(self)
        self.layer = layer

    def fieldDefinition(self, field):
        return field

    def convert(self, idx, value):
        return value

    def clone(self):
        return FieldValueConverter(self)

layer = iface.activeLayer()

myoptions = QgsVectorFileWriter.SaveVectorOptions()
myconverter = CustomFieldValueConverter(layer)
myoptions.fieldValueConverter = myconverter
myoptions.driverName = 'GPKG'
context = QgsProject.instance().transformContext()
mypath = '/tmp/output.gpkg'
# write_result, error_message = QgsVectorFileWriter.writeAsVectorFormatV2(layer, mypath, context, myoptions)
# since QGIS 3.20 you can use writeAsVectorFormatV3
error_message = QgsVectorFileWriter.writeAsVectorFormatV3(layer, mypath, context, myoptions)

print(write_result, error_message)

The code works as it is from the console, exporting the active layer. Change the output path, if necessary.

Your Answer

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

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