简体   繁体   中英

Sorting numeric column in QTableWidget

I am trying to sort a numeric column in QTableWidget using PyQT5. I read some examples and tried but it doesn't work very well. It always give same result back.

This is before sorting

分拣前

This is after sorting

排序后

The problem is that using strings in the QTableWidgetItem instead of numbers. Given this, there are several options:

  • Store numbers instead of strings:

     import sys from PyQt5 import QtCore, QtWidgets app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QTableWidget(100, 1) w.setSortingEnabled(True) for i in range(w.rowCount()): it = QtWidgets.QTableWidgetItem()  w.setItem(i, 0, it) w.resize(640, 480) w.show() sys.exit(app.exec_())
  • Override the __lt__ method of QTableWidgetItem:

     import sys from PyQt5 import QtWidgets class TableWidgetItem(QtWidgets.QTableWidgetItem): def __lt__(self, other): try: return float(self.text()) < float(other.text()) except ValueError: return super().__lt__(other) app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QTableWidget(100, 1) w.setSortingEnabled(True) for i in range(w.rowCount()): it = TableWidgetItem(str(i)) w.setItem(i, 0, it) w.resize(640, 480) w.show() sys.exit(app.exec_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM