Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 984
PedroBiel Avatar asked Feb 20 '26 02:02

PedroBiel


1 Answers

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_())
like image 123
eyllanesc Avatar answered Feb 22 '26 14:02

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!