3

I have a table with multiple fields with widget types configured (value map, checkbox, date/time).

What I need is to export this table in a geopackage, using this in a PyQGIS script, using the "Replace all selected raw field values by displayed values".

rutaBase = QgsProject.instance().absolutePath()
rutaGpkg = rutaBase + '/geopackage.gpkg'
table = QgsProject.instance().mapLayersByName('tblActuaciones')[0]

opt = QgsVectorFileWriter.SaveVectorOptions()
opt.layerName = 'exported_table'
opt.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
opt.fieldValueConverter = QgsVectorFileWriter.FieldValueConverter
QgsVectorFileWriter.writeAsVectorFormat(table, rutaGpkg, opt)

But I get this error:

TypeError: sip.wrappertype cannot be converted to qgis._core.FieldValueConverter in this context

enter image description here

1 Answer 1

2

Use opt.fieldValueConverter = QgsVectorFileWriter.FieldValueConverter() instead of opt.fieldValueConverter = QgsVectorFileWriter.FieldValueConverter as it's a class not an enum

I've tested below code and it works without failure/crash (QGIS 3.16 on Ubuntu 18.04). The only difference with your script are: did not change in options actionOnExistingFile, set driverName explicitly to GPKG and use the class like explained in 1st part of my initial answer.

source_layer = iface.activeLayer() # Using a shp point as an input
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = 'GPKG'
options.layerName = 'exported_table'
fieldValueConverter = QgsVectorFileWriter.FieldValueConverter()

dest_file_name = '/tmp/out.gpkg'
write_result, error_message = QgsVectorFileWriter.writeAsVectorFormat(
    source_layer,
    dest_file_name,
    options)
6
  • Thanks @thomasg77, but If I do that QGIS crashes... Commented Feb 12, 2021 at 8:18
  • This works fine although it overwrites the geopackage file and I've other layers in it. But if I leave the actionOnExsistinFile it works and QGIS does not crashes. The problem is that it only replace the boolean and date fields, but not the value map fields. Commented Feb 14, 2021 at 11:29
  • For the "the value map fields" not working, did you try with the GUI before? To be sure if error is QGIS overall or only in PyQGIS.
    – ThomasG77
    Commented Feb 14, 2021 at 12:24
  • Yes, I tried it using the GUI before starting the script just to see if it is possible to do so and it works fine. Commented Feb 14, 2021 at 13:31
  • FYI, made an answer related at gis.stackexchange.com/questions/389698/…
    – ThomasG77
    Commented Mar 12, 2021 at 10:20

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.