3

I would like to set the editor widget type for a a given field of a layer with PyQGIS. The actual widget type can be retrieved for example like

>>> iface.activeLayer().editFormConfig().widgetType('text_x')
u'TextEdit'

How can I set this to editor widget type Hidden, for example?

I tried:

>>> iface.activeLayer().editFormConfig().setWidgetType('text_x', u'Hidden')
Traceback (most recent call last):
 File "<input>", line 1, in <module>
TypeError: QgsEditFormConfig.setWidgetType(int, QString): argument 1 has unexpected type 'str'

And also:

from qgis.gui import *
iface.activeLayer().editFormConfig().setWidgetType('text_x', QgsHiddenWidgetWrapper)
Traceback (most recent call last):
 File "<input>", line 1, in <module>
NameError: name 'QgsHiddenWidgetWrapper' is not defined

From the doku https://qgis.org/api/2.18/classQgsEditFormConfig.html#afc55a3ae3b331225dd69b561d0d437bd the correct 'spelling' of setting up the widget type is not so clear to me.

2

Just found an answer on my own (monday mornings...). I just did not see that setWidgetType() wants the field ID as input, not the field name, so I have to

>>> iface.activeLayer().fields().indexFromName('text_x')
7
iface.activeLayer().editFormConfig().setWidgetType(7, u'Hidden')

or using setEditorWidgetV2() directly on the layer:

iface.activeLayer().setEditorWidgetV2(7, u'Hidden')

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.