7

I would like to make by programmation (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?

13

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

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 )

NOTE: For QGIS 3 you can configure the Value Map widget in this way

fieldIndex = layer.fields().indexFromName( 'myField' )
editor_widget_setup = QgsEditorWidgetSetup( 'ValueMap', {
                         'map': {u'Description 1': u'value1', 
                                 u'Description 2': u'value2'}
                        }
                      )
layer.setEditorWidgetSetup( fieldIndex, editor_widget_setup )
  • setEditorWidgetV2Config(...) works, but I get a deprecation warning, are there other approaches? – Jochen Schwarze May 15 '17 at 14:35
  • 1
    Added a note showing how to configure Value Maps for QGIS3. – Germán Carrillo May 16 '17 at 4:23
  • @GermánCarrillo is there a way to set a function from .qgis2\python\expressions instead of value1 ? – Hicham Zouarhi Aug 2 '17 at 15:27
  • Is it possible to have multiple selection option with map value ? – Anass Ayar Oct 15 '18 at 14:56
  • I don't think so. You would need to use Value Relation for that. – Germán Carrillo Oct 15 '18 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.