0

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)

1 Answer 1

1

give the following code a go. I've changed the logic round a bit but it seems to work for me using the python window in QGIS 3.10 . When geopackage is true it saves out the 'in memory' layer, then uses the index of the field 'active' to set the default value to true. I don't know why, but if you set the default value for the field on the in memory layer first, then save it to gpkg it doesn't save out the default value setting.

useGeopackage = True
vl = QgsVectorLayer("Point", 'name', "memory")
pr = vl.dataProvider()
# add field
f1 = QgsField("active", QVariant.Bool) 
f1.setDefaultValueDefinition(QgsDefaultValue('True'))
pr.addAttributes([f1])
vl.updateFields()
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')
    idx = vl.fields().indexFromName('active')
    vl.setDefaultValueDefinition(idx, QgsDefaultValue('True'))


QgsProject.instance().addMapLayer(vl)
1
  • Thx a lot for your solution. This works fine for me to. It is also strange that if you shift the whole field creation and defaultvalue setup behind the file writer and read stuff it doesn't work either. So it seems that the setDefaultValue function needs to be called on the layer object level instead of the field object.
    – Jakob
    Oct 17, 2020 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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