Saturday 28 September 2019

qgis - How to create predefined values in a field in PyQGIS?


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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...