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
35.8k5 gold badges77 silver badges152 bronze badges
asked Mar 2, 2017 at 16:24
0

1 Answer 1

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.