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?

  • Next time, tell us what you've tried. Feb 11, 2015 at 19:36
  • 1
    Sure next time it will be posted.
    – User123
    Feb 12, 2015 at 4:03

1 Answer 1


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.

  • Is it not the same as setting a layers Properties > Fields > Edit Widget to Unique Values?
    – Jakob
    Feb 12, 2015 at 7:57
  • @gcarrillo: The above snippet works fine for shapefile layer. When I tried with spatialite layer, it throws an error "QCombo.addItems(QStringList): argument 1 has unexpected type 'list'. I am curious why this happens in spatialite layer.
    – User123
    Feb 12, 2015 at 12:50
  • @Jakob Not really, Ahamed wants to put a ComboBox in his plugin's dialog. Feb 12, 2015 at 13:11
  • @AhamedFarook Cannot replicate the issue you mentioned. I tried on a SpatiaLite layer and still get unique values to populate the QComboBox. Did you change something in the code? Feb 12, 2015 at 14:46
  • I havenot change anything in the code. But the same code still works fine for shapefile layer and gives an error for spatialite layer. Wondering how?
    – User123
    Feb 12, 2015 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.