6

I am still very new to Qt but I am developing a type of calculator and want to use a combobox to select a coefficient. I have had success creating a combobox with a liststore in pyGT but it appears pyQT is quite different.

I am having a hard time wrapping my head around the data models and list models. Essentially I want to have a name show up in the combobox and have the value of that name get passed to the calculator equation. Everything I have seen so far has been just for single entries and not 'associated' entries.

Can anyone explain or point me to a tutorial to walk me through what I am trying to accomplish?

Judson
  • 73
  • 1
  • 1
  • 4

1 Answers1

10

You can use addItem to add a name (text) with an associated value (data):

    self.combo.addItem('Foo', 23)
    self.combo.addItem('Bar', 42)

A slot can be connected to the activated signal of the combo box, which will send the index of the item selected by the user:

    self.combo.activated.connect(self.handleActivated)

You can then use itemText and itemData to access the name and value via the index parameter:

    def handleActivated(self, index):
        print(self.combo.itemText(index))
        print(self.combo.itemData(index))
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Note: if you do "itemData" pyqt returns QtVariant class, to get the value you can use self.combo.itemData(index).toString() – Jaziel_Inc Jun 04 '20 at 13:24
  • 2
    @Jaziel_Inc That is only needed in PyQt4, which is now obsolete and no longer supported. This question is about PyQt5. – ekhumoro Jun 04 '20 at 15:10