Reputation: 23
There are column with numbers only. But it sorts like that:
And how this part of code looks like:
self.table = QTableWidget(self)
self.table.setColumnCount(5)
self.table.setRowCount(0)
self.table.setSortingEnabled(True)
self.table.sortByColumn(1, Qt.DescendingOrder)
And there are not just 4 or 5 rows, it cant be 10,100, or more, because i have a button to insert row with custom number in this 1st column. And some buttons to edit items in this column (but it still only numbers)
Upvotes: 2
Views: 3890
Reputation: 48260
If you insert the item data as text strings, they will always use the alphanumerical ordering, so numbers from 1 to 20 will be sorted like this:
1, 10, 2, 20, 3, 4, ...
To achieve numerical ordering, the data has to be stored as numeric, and this can be done by using setData(role, value)
:
from random import randrange
class MyWindow(QtWidgets.QWidget):
# ...
def addData(self):
for row in range(10):
item = QtWidgets.QTableWidgetItem()
item.setData(QtCore.Qt.DisplayRole, randrange(10000))
self.table.setItem(row, 1, item)
Alternatively, you can subclass the QTableWidgetItem, as shown in this answer: Sorting in pyqt tablewidget.
Upvotes: 6