Friday, 26 February 2016

qgis - How to change the edit widget for fields in a layer with PyQGIS?


Is possible change the edit widget with PyQGIS?


I have made an extension that loads a PostGIS layer and I want to edit the date fields with the date widget by default without any change in the settings of layer ( "layer properties dialog").



Answer



You can use the method setEditorWidgetV2() from QgsVectorLayer.


To set the edit widget of a field to DateTime, do this:


vLayer.setEditorWidgetV2( fieldIndex, 'DateTime' )


Parameters can be set via a dictionary of key-values, like this:


vLayer.setEditorWidgetV2Config( fieldIndex, {'display_format': 'yyyy-MM-dd', 'allow_null': False, 'field_format': 'yyyy-MM-dd', 'calendar_popup': True})

enter image description here


You can find a description of the available options at the QgsDateTimeEditWrapper documentation.


A list of available widgets can be found here.




On the other hand, if you want all your Date fields to have the DateTime edit widget, you could do something like this:


fields = vLayer.dataProvider().fields()

dateFields = []
# Get indices of date fields
for field in fields:
if field.typeName() == 'Date':
dateFields.append( vLayer.fieldNameIndex(field.name()) )

# Set the DateTime editor widget for date fields
for dateField in dateFields:
vLayer.setEditorWidgetV2( dateField, 'DateTime' )

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...