6

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

8

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' )
2
  • Is possible to initiate the calendar on Monday? I know that QCalendarWidget has this option, but I don't know if it is possible to change it this way. – Alexandre Mar 3 '15 at 15:32
  • Probably not, at least I couldn't find such option. – Germán Carrillo Mar 3 '15 at 16:03

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.