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.