Search code examples
pythonpyqtqcombobox

Pyqt Combobox like Html


I'm using PyQt5 and I want to assign a value for each item in QComboBox, like the HTML combobox.

I know I can get the selected item or index, but I want to get the value.

For example in HTML:

 <select>
  <option value="0.18">Name 1</option>
  <option value="0.36">Name 2</option>
  <option value="0.40">Name 3</option>
  <option value="0.43">Name 4</option>
</select> 

Is it possible to do something like this?


Solution

  • You can do this using userData and here is a working example

    from PyQt4 import QtGui, QtCore
    import sys
    
    
    class Example(QtGui.QWidget):
        def __init__(self):
            super(Example, self).__init__()
            self.initUI()
    
        def initUI(self):
            self.btn = QtGui.QComboBox(self)
            dataToAdd = {"Name 1" : 0.18, "Name 2" : 0.36, "Name 3" : 0.41, "Name 4" : 0.43,}
            self.btn.addItem("Select")
            for eachItem in dataToAdd:
                val = dataToAdd[eachItem]
                self.btn.addItem(eachItem, userData=QtCore.QVariant(str(val)))
            self.btn.move(20, 20)
            self.setGeometry(300, 300, 290, 150)
            self.btn.currentIndexChanged.connect(self.foo)
            self.show()
    
        def foo(self, value):
            itemValue = self.btn.itemData(value).toString()
            itemText = self.btn.itemText(value)
            print itemValue, "====", itemText
    
    def main():
        app = QtGui.QApplication(sys.argv)
        ex = Example()
        sys.exit(app.exec_())
    
    if __name__ == '__main__':
        main()
    

    Please check doc's for more details http://pyqt.sourceforge.net/Docs/PyQt4/qcombobox.html#addItem