I'm trying to change an field to a default string everytime an polygon is created in attributes form.

For now I have seen Alexandro code and based on that I have something like this:

layername = "ZAPM"
layer = QgsProject.instance().mapLayersByName(layername)[0]
field = "ID_PM"
list_values = {"ID_PM001":"ID_PM001"}

def field_to_value_map(layer, field, list_values):
    config = {'map' : list_values}
    widget_setup = QgsEditorWidgetSetup('ValueMap',config)
    field_idx = layer.fields().indexFromName(field)
    layer.setEditorWidgetSetup(field_idx, widget_setup)

field_to_value_map(layer, field, list_values)

enter image description here

This code is great, but it's half completed, I want the form field to be a string, not dropdown.

1 Answer 1


The first thing I did find was to get the editorWidgetSetup type and config

After some search, and using this script to find both type and config, this is my simple final code:

layername = "layer_name"
layer = QgsProject.instance().mapLayersByName(layername)[0]
field = "field_name"

def zapm(layer, field):
    config =  {'IsMultiline': False, 'UseHtml': False}

    layer.editFormConfig().setWidgetConfig("TextEdit", config)
    default_value = QgsDefaultValue()
    default_value.setExpression("'Your value'") // Keep the ''  inside of ""
    field_index = layer.fields().indexFromName(field)
    # Set the default value for the specific field
    layer.setDefaultValueDefinition(field_index, default_value)

zapm(layer, field)

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.