I try to create a vector layer with some field values which should use a QgsDefaultValue.
It works fine if I use an in-memory layer (useGeopackage=False
) but fails (no default value) if I use a geopackage layer.
If I manually set the default value of the geopackage layer using the GUI it work fine however.
A minimal example looks like:
useGeopackage = True
vl = QgsVectorLayer("Point", 'name', "memory")
if useGeopackage:
# save layer to geopackage
path = 'test.gpkg'
options = QgsVectorFileWriter.SaveVectorOptions()
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile
options.layerName = 'layerName'
QgsVectorFileWriter.writeAsVectorFormat(vl, path, options)
del vl
# load the newly created layer
vl = QgsVectorLayer(path+'|layername='+'layerName', 'name', 'ogr')
pr = vl.dataProvider()
# add field
f1 = QgsField("active", QVariant.Bool)
f1.setDefaultValueDefinition(QgsDefaultValue('true'))
pr.addAttributes([f1])
vl.updateFields()
QgsProject.instance().addMapLayer(vl)