Pyqt5 ComboBox sorts data automatically

Viewed 261

When i insert a dictionary like {"B": 1, "A": 2, "D": 3, "C": 4} into a PyQt5 ComboBox, the dict will be alphabetically sorted by the keys. How can i prevent this and keep the original order?

Example:

    dictionary = {"B": 1, "A": 2, "D": 3, "C": 4}
    self.comboBox.addItem("Test", dictionary)
    print(dictionary)
    print(self.comboBox.itemData(0))

This outputs:

    {'B': 1, 'A': 2, 'D': 3, 'C': 4}
    {'A': 2, 'B': 1, 'C': 4, 'D': 3}
1 Answers

It seems that it is a bug (or at least an unexpected behavior) caused by the way PyQt5 (and PySide2) stores dictionaries, a workaround is to use OrderedDict:

import collections

dictionary = {"B": 1, "A": 2, "D": 3, "C": 4}
print(dictionary)

self.comboBox = QtWidgets.QComboBox()
self.comboBox.addItem("Test", collections.OrderedDict(dictionary))

d = dict(self.comboBox.itemData(0))

print(d)

Output:

{'B': 1, 'A': 2, 'D': 3, 'C': 4}
{'B': 1, 'A': 2, 'D': 3, 'C': 4}
Related