4

When I add a point in PyQGIS and then the object form opens, I want the attributes to be filled with given input or selection options. I want to prevent free text input. Without PyQGIS it is possible under Layer-Properties and attribute form with value mapping etc. See pic 1

enter image description here

In my case, my plugin loads a layer directly from the PostgreSQL database. Our users should not make changes in the layer properties. With this code I get the object form of the last object.:

layer = iface.activeLayer()
features = layer.getFeatures()
feature_list = list(f for f in features)
feat = feature_list[-1]
iface.openFeatureForm(layer, feat, True)

enter image description here

How can I access the attribute selection in openFeatureForm with PyQGIS?

For example, I want the "bezirk" column to have only two options.

0

1 Answer 1

9

I used this code by Alexandre Neto and this answer to Value map from database in QGIS 3 to provide my answer.

Here is a code that works for me :

layername = "test_data"    
layer = QgsProject.instance().mapLayersByName(layername)[0]
field = "bezirk"
list_values = {"Bezirk 1":1, "Bezirk 2":2}

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)

This is the result I obtain :

Result

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.