I have created a layer in python with 3 fields: fields = [QgsField("name", QVariant.String),QgsField("code", QVariant.String),QgsField("email", QVariant.String)]
As per this thread https://gis.stackexchange.com/questions/456730/use-pyqgis-to-load-value-map-against-attribute, I have tried to give the code field a Value Map (widget type):
# Set widget type for the "code" field
code_field_index = layer.fields().indexFromName("code")
widget_setup = QgsEditorWidgetSetup('ValueMap', {'Map': {'1': 'Option 1', '2': 'Option 2', '3': 'Option 3'}})
layer.setEditorWidgetSetup(code_field_index, widget_setup)
I print each field’s widget type (field.editorWidgetSetup().type()
) and as wanted the code field has widget type ‘ValueMap’.
However when I export the layer to a geopackage:
# Export layer to GeoPackage
export_path = "path/to/your_geopackage.gpkg"
QgsVectorFileWriter.writeAsVectorFormat(layer, export_path, "UTF-8", layer.crs(), "GPKG")
And drag teh resulting geopackage into QGIS the code field has the ‘TextEdit’ widget type instead of ‘ValueMap’. What went wrong?
I have tried reading the PyQGIS documentation on QgsEditorWidgetSetup but found nothing to help.
Bendigo McAllan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.