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?

0

1 Answer 1

18

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 )
5
  • 1
    setEditorWidgetV2Config(...) works, but I get a deprecation warning, are there other approaches? May 15, 2017 at 14:35
  • 1
    Added a note showing how to configure Value Maps for QGIS3. May 16, 2017 at 4:23
  • @GermánCarrillo is there a way to set a function from .qgis2\python\expressions instead of value1 ? Aug 2, 2017 at 15:27
  • Is it possible to have multiple selection option with map value ? Oct 15, 2018 at 14:56
  • I don't think so. You would need to use Value Relation for that. Oct 15, 2018 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.