1

I'm new to the QGIS software and am attempting to change the widget type to 'Unique Value' (by default, it's 'Text Edit') using PyQGIS.

Unique Value-Editable

I have more than 20 fields in a layer for which I want to set the Widget Type as Unique Values and make them Editable. However, manually setting this up is taking too much time. I've tried the following code:

from qgis.core import QgsEditorWidgetSetup

layer = iface.activeLayer()
field_index = layer.fields().indexFromName('POINT_ADDR, STEET_ROAD, LANDMARK')

if field_index != -1:
    layer.setEditorWidgetSetup(field_index, QgsEditorWidgetSetup('Unique Values', {}))
    layer.startEditing()   
    layer.commitChanges()
else:
    print("Field 'Your Field Name' does not exist in the layer.")

After running this code QGIS will crash and will close.

Are there any alternative ways to overcome this problem?

2
  • 1
    You can only get the index of one field at a time with indexFromName() method. You will have to loop through the fields one by one. Also, you need to startEditing() before making changes, and then commitChanges() afterwards.
    – Andre Geo
    Commented Nov 19, 2023 at 16:25
  • Thank you for your assistance It resolved the issue! Commented Nov 21, 2023 at 16:19

1 Answer 1

4

Try this:

layer = iface.activeLayer()

# start with a list of your fields to edit
mt20_fields = ['POINT_ADDR', 'STEET_ROAD', 'LANDMARK']

# fields must be iterated through:
for field in mt20_fields:
    field_index = layer.fields().indexFromName(field)
    if field_index == -1:
        # if field does not exist, skip to the next one
        print(f"field {field} not found")
        continue
    # otherwise, set widget settings to type='UniqueValues' and config={'Editable':True}
    layer.setEditorWidgetSetup(field_index, QgsEditorWidgetSetup('UniqueValues', {'Editable':True}))

Note that 'UniqueValues' needs to be one word. And there is no need to enable editing or commit changes on the layer.

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.