2

There are many questions like this but either they propose to implement a new method to update values or describe how to set default values for fields in GUI.

I'm writing a QgsProcessingAlgorithm and need to set default values when modifying fields using the QgsEditorWidgetSetup either for 'KeyValue' if the fieldtype is hstore or 'TextEdit' if it's some kind of String-field. Here's what I've tried (for 'TextEdit' because it's simpler):

sourceLayer.setEditorWidgetSetup(index, QgsEditorWidgetSetup('TextEdit', 
{
   'DefaultValue': 'DefValue',
   'Defaults': 'DefValue',
   'Default': 'DefValue',
   'IsMultiline': 'True',
   'UseHtml': 'False'
}

The properties 'IsMultiline' and 'UseHtml' work flawlessly but none of the defaults is accepted.

A often proposed approach is to use the Python console to get the QgsEditorWidgetSetup config of a field configured via GUI. This is done by the following code:

layer = qgis.utils.iface.activeLayer()
layer.fields().names()
idx = layer.fields().indexFromName('text')
field = layer.fields()[idx]
field.editorWidgetSetup().config()

Unfortunately the output is just: {'IsMultiline': False, 'UseHtml': False} Although of course the default value I configured is working fine when I add new features through the attribute table.

Any ideas?

1 Answer 1

3

You can set a layer's field default value with this following code, by using the QgsVectorLayer's setDefaultValueDefinition method :

layer = qgis.utils.iface.activeLayer()
my_field = layer.fields().names()[1]  # second field
idx = layer.fields().indexFromName(my_field)
default_value = QgsDefaultValue()
default_value.setExpression("'This is the DefaultValue'")
layer.setDefaultValueDefinition(idx, default_value)
6
  • Thanks so much J :-) However, from the PyQGIS API perspective this isn't very straightforward. Furthermore, there isn't a getDefaultValueDefinition, is there?
    – Sickboy
    Commented Jun 27, 2022 at 6:47
  • You have field.defaultValueDefinition() or layer.defaultValueDefinition(idx). Commented Jun 27, 2022 at 7:38
  • Thanks :-) However, a set-method but no get-method isn't very straightforward again.
    – Sickboy
    Commented Jun 28, 2022 at 4:43
  • @Sickboy: that is how Qt is designed in general, take a look here setter setCurrentIndex, getter currentIndex : doc.qt.io/qt-6/qcombobox.html#currentIndex-prop. Commented Jun 28, 2022 at 6:58
  • @Sickboy: if my answer is valid and answers your question, don't forget to accept it. Commented Jun 30, 2022 at 9:05

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.