[GIS] Adding field values to a QComboBox in PyQGIS

pyqgispythonqgisqgis-plugins

I have a layer say 'Cities'. There is a column called 'NAME_1' in the layer. My GUI has a QComboBox in which i want the values of column 'NAME_1' alone to be displayed in the drop down of the combo box.

Can anyone help me in providing snippet in Python for getting a value from a particular column and displaying it in the combo box?

Best Answer

Since there is no custom QGIS GUI widget for that (at least I couldn't find it), you could try something like this:

from PyQt4.QtGui import QComboBox

lyr = iface.activeLayer()
idx = lyr.dataProvider().fieldNameIndex( 'NAME_1' ) 
uv = lyr.dataProvider().uniqueValues( idx )
cb = QComboBox()
cb.addItems( uv )

Note that we are obtaining unique values of the field NAME_1, because I guess that's the desired behavior. Otherwise you would be showing your users a list with repeated values, which is not really ideal for a QComboBox.

Related Question