按数字排序QListWidget

时间:2018-05-17 08:49:01

标签: python python-3.x pyqt4 qlistwidget

我有QListWidget这些项目:

1
10
100
11
110
111
12

我想按数字订购列表中的项目:

1
10
11
12
100
110
111

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

默认情况下,QListWidget会根据文本对元素进行排序,如果您想根据与文本相关联的数值进行排序,则必须创建自定义QListWidgetItem并覆盖方法__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_())