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?
1 Answer 1
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
-
1
setEditorWidgetV2Config(...)
works, but I get a deprecation warning, are there other approaches?Jochen Schwarze– Jochen Schwarze2017年05月15日 14:35:57 +00:00Commented May 15, 2017 at 14:35 -
1Added a note showing how to configure Value Maps for QGIS3.Germán Carrillo– Germán Carrillo2017年05月16日 04:23:02 +00:00Commented May 16, 2017 at 4:23
-
@GermánCarrillo is there a way to set a function from
.qgis2\python\expressions
instead of value1 ?Hicham Zouarhi– Hicham Zouarhi2017年08月02日 15:27:15 +00:00Commented Aug 2, 2017 at 15:27 -
Is it possible to have multiple selection option with map value ?ayar anasse– ayar anasse2018年10月15日 14:56:06 +00:00Commented Oct 15, 2018 at 14:56
-
I don't think so. You would need to use Value Relation for that.Germán Carrillo– Germán Carrillo2018年10月15日 15:53:47 +00:00Commented Oct 15, 2018 at 15:53
lang-py