1

I am trying to create a combobox using PyQGIS for a custom plugin. The values in the combobox have to come from a database - I can't use a .csv or a layer because the values in the combobox will change over time. I've defined my field as Value Map in my default style, and am using the following code to try and create my list of values (based on this example).

SQL_departements = "SELECT (string_agg('u'''||dept.description||''' : u'''||dept.valeur,''', ' ORDER BY description))||'''' FROM ref.dept;"
    cur_qgis.execute(SQL_departements)
    departements = cur_qgis.fetchone()
    dept_rat_index = layer.fields().indexFromName('dept_rattachement')
    dept_rat_widget_setup = QgsEditorWidgetSetup( 'ValueMap', {
                         'map': {departements[0]}
                        }
                      )
    layer.setEditorWidgetSetup(dept_rat_index, dept_rat_widget_setup )

(For the record, the result of print(departements[0]) is u'01 - Ain' : u'01', u'07 - Ardèche' : u'07', u'26 - Drôme' : u'26', u'42 - Loire' : u'42', u'69 - Rhône' : u'69', u'Métropole de Lyon' : u'ml')

So far, I haven't have any success. The combobox in my custom form remains empty.

What is the correct code I should use to be able to fill my Value map list using PyQGIS?

0

Finally got it right through some reverse engineering (got the idea from this Q&A : Qgis 3 : QgsEditorWidgetSetup for date). The correct code to use is :

SQL_departements = "SELECT description,valeur FROM ref.dept;"
cur_qgis.execute(SQL_departements)
departements = cur_qgis.fetchall()
dept_rat_index = layer.fields().indexFromName('dept_rattachement')
departements = dict(departements)
type = 'ValueMap'
config = {'map' : departements}
dept_rat_widget_setup = QgsEditorWidgetSetup(type,config)
layer.setEditorWidgetSetup(dept_rat_index,dept_rat_widget_setup)

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.