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?
Answer
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 )
No comments:
Post a Comment