Search code examples
pythonpython-3.xpyqt4qlistwidget

Sorting a QListWidget by numbers


I have a QListWidget with these items:

1
10
100
11
110
111
12

And I want to order the items of the list by numbers:

1
10
11
12
100
110
111

Any idea?


Solution

  • By default QListWidget will order the elements with respect to the text, if you want to be ordered with respect to the numeric value that is associated with the text you must create a custom QListWidgetItem and overwrite the method __lt__:

    import sys
    
    from PyQt4.QtGui import QApplication, QListWidget, QListWidgetItem
    from PyQt4.QtCore import Qt
    
    class ListWidgetItem(QListWidgetItem):
        def __lt__(self, other):
            try:
                return float(self.text()) < float(other.text())
            except Exception:
                return QListWidgetItem.__lt__(self, other)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = QListWidget()
        for i in [1, 10, 100, 11, 110, 111, 12]:
            w.addItem(ListWidgetItem(str(i)))
        w.sortItems()
        w.show()
        sys.exit(app.exec_())