blade_runner blade_runner - 2 months ago 10
Python Question

Order QComboBox items alphabetically regardless of index

I have a list of plants arranged in a specific order which should be keept and expressed by the index. In a QComboBox the plants however should be displayed in alphabetical order.

To do so I tried this:

self.plant = QComboBox(self)
self.plant.insertItem(4, "A")
self.plant.insertItem(1, "B")
self.plant.insertItem(3, "C")
self.plant.insertItem(0, "D")
self.plant.insertItem(5, "E")
self.plant.insertItem(2, "F")


The resulting ComboBox however is ordered like D A F B C E

Looks like my approach isn't working...

EDIT (further explanation of question):
The plants are listed in historical order in a database (plant D is the oldest, then came B, F, C, A - E has been added recently). The script needs to know which plant has been selected - I'd like to do this with the index and an associative array.
To ease plant selection (there are more than six of them) they should be listed in alphabetical order in the dropdown list.

If I want to add a new plant named Ca, I'd edit the script like this:

self.plant = QComboBox(self)
self.plant.insertItem(4, "A")
self.plant.insertItem(1, "B")
self.plant.insertItem(3, "C")
self.plant.insertItem(6, "Ca")
self.plant.insertItem(0, "D")
self.plant.insertItem(5, "E")
self.plant.insertItem(2, "F")


I hope this clearifies the meaning of my question: It should be possible to easily place a new plant at the alphabeticaly right position without changing all the other indexes.

In a next step the right task should be executed according to the plant selection:

options = {0 : D,
1 : B,
2 : F,
3 : C,
4 : A,
5 : E,
6 : Ca,
}

def D():
#do task for plant D

def B():
#do task for plant D
...

Answer

QCombobox is always ordered by index. If you really need to have them alphabetical and have some numerical data stored then set the data for each item.

cb = QComboBox()
cb.addItem("A", 4)
cb.addItem("B")
cb.setItemData(1, 1, Qt.UserRole)

# To get the data. or cb.itemData(cb.currentIndex(), Qt.UserRole)
cb.itemData(0, Qt.UserRole)