-1

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?

xralf
  • 3,312
  • 45
  • 129
  • 200
  • why would you like to have only 5 and 19 index instead of 0 and 1 ? If you need these values maybe you could use `void QComboBox::insertItem(int index, const QString &text, const QVariant &userData = QVariant())` and pass that 5/19 on userData param – Megasa3 Jun 07 '22 at 07:07
  • @Megasa3 Because I need to query database with index 5 or 19. – xralf Jun 07 '22 at 07:09
  • And using the option I told you? You can access that info later with currentData or itemData methods instead of currentIndex – Megasa3 Jun 07 '22 at 07:14
  • @Megasa3 Could you please write it in Python? – xralf Jun 07 '22 at 07:19
  • I'm afraid not. Just know about Qt with C++ and wanted to help but it has to be something like `klients.insertItem(0, "x", 5);` and access it with something like `value =klients.itemData(klients.currentIndex());` – Megasa3 Jun 07 '22 at 07:25
  • I see you acepted the answer of musicamante which is the same I was saying so I guess it worked :) – Megasa3 Jun 07 '22 at 08:16

1 Answers1

1

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())
musicamante
  • 41,230
  • 6
  • 33
  • 58