Anh Tu
Anh Tu

Reputation: 85

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

Before sorting

This is after sorting

After sorting

Upvotes: 0

Views: 793

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

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()
          it.setData(QtCore.Qt.DisplayRole, i)
          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_())
    

Upvotes: 1

Related Questions