Search code examples
pyqt5qcombobox

QComboBox getting wrong index


I have this combobox.

 klients = qtw.QComboBox(self)
 klients.insertItem(5, "x")
 klients.insertItem(19, "y")

when I later write this code in button clicked event:

print(klients.currentIndex())

It prints 0 or 1 instead of 5 or 19. How can I achieve it prints 5 or 19?


Solution

  • QComboBox item management works just like a list: after creating a new list, doing list.insert(5, "x") will add "x" at the first index, which is quite obvious, since the list is empty.

    If you want to have internal reference of custom data, then use the userData argument of addItem():

    klients.addItem("x", 5)
    klients.addItem("y", 19)
    

    and then retrieve it with currentData():

    data = klients.currentData()
    # equivalent to
    data = klients.itemData(klients.currentIndex())