11

I would like to make programmatically (with Python) the same thing than we can do directly in QGIS when you create a list of values for a field.

I would like to create a new field and specify a list of possible values for this field. I didn't find any function for that in the API. Is there anyone who has the solution?

Taras
  • 32,823
  • 4
  • 66
  • 137
Etienne
  • 537
  • 2
  • 10

1 Answers1

19

You need to assign and configure a ValueMap widget to your layer's field in this way:

QGIS 3.x

fieldIndex = layer.fields().indexFromName( 'myField' )
editor_widget_setup = QgsEditorWidgetSetup( 'ValueMap', {
                         'map': {'Description 1': 'value1', 
                                 'Description 2': 'value2'}
                        }
                      )
layer.setEditorWidgetSetup( fieldIndex, editor_widget_setup )

QGIS 2.x

fieldIndex = layer.fieldNameIndex( 'myField' )
layer.setEditorWidgetV2( fieldIndex, 'ValueMap' )
values = {u'Description 1': u'value1', 
          u'Description 2': u'value2', 
          u'Description 3': u'value3'}
layer.setEditorWidgetV2Config( fieldIndex, values )
Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178