31

I have A LOT of QComboBoxes, and at a certain point, I need to fetch every item of a particular QComboBox to iterate through.
Although I could just have a list of items that correspond to the items in the QComboBox, I'd rather get them straight from the widget itself (there are a huge amount of QComboBoxes with many items each).

Is there any functions / methods that will do this for me?
(Eg:

 QComboBoxName.allItems()

)
I've looked through the class reference but couldn't find anything relevant.

I've thought of a few messy methods, but I don't like them.
(Like iterating through the QComboBox by changing the index and getting the item, etc).


Python 2.7.1
IDLE 1.8
Windows 7
PyQt4

NorthCat
  • 9,643
  • 16
  • 47
  • 50
Anti Earth
  • 4,671
  • 13
  • 52
  • 83
  • This is an old post, but for completeness, it might be worth considering using a model to populate the combo and working with that. – Lorem Ipsum Aug 18 '21 at 21:38

2 Answers2

70

As far as I can tell, you can just reference an item using .itemText():

AllItems = [QComboBoxName.itemText(i) for i in range(QComboBoxName.count())]
Anti Earth
  • 4,671
  • 13
  • 52
  • 83
Blender
  • 289,723
  • 53
  • 439
  • 496
0

Building on the accepted answer, you can actually give you combobox a method callable using combo_box.allItems(), by doing this:

    setattr(combo_box, "allItems", lambda: [combo_box.itemText(i) for i in range(self.ui.combo_box.count())])
    print(combo_box.allItems()) # Works just fine!

I believe it has to be done in the scope where combo_box was born, otherwise setattr fails. Tested in PyQt5 and Python 3.7.

Guimoute
  • 4,407
  • 3
  • 12
  • 28