[PyQt] How to make sort working when click the column
davecortesi at gmail.com
Fri May 16 01:55:20 BST 2014
不坏阿峰 <onlydebian at gmail.com> writes,
> i have use Qtablewidget to display my data.
while in the tablewidget it is store like string.
when click the column ,it sort by alphabetical order not by numerically.
QTableWidget and QTableView implement a simple alphanumeric sort of
strings. It is not even locale-aware.
To sort in a different way, for example to sort on numeric value, I think
you must leave the QTableWidget, go to QTableView and then add a
QSortFilterProxyModel. There is an example (in C++ of course) here:
You must make a subclass of QSortFilterProxyModel in which you write your
own method lessThan(left,right). In this method you compare any two table
items from one column, and return True if the item at the "left" model
index is less than the model at the "right" model index.
In this code you can, for example, convert strings to integers or to float
or to date-time and compare them in that format.
The following is NOT TESTED, but gives the general idea.
> class mySortFilterProxy(QSortFilterProxyModel):
> def __init__(self, parent=None):
> # compare table elements of column 2 as float numbers
> def lessThan(self, left, right):
> if left.column() == 2 :
> return float(self.sourceModel().data(left)) <
> # not column 2, compare as strings
> return self.sourceModel().data(left) <
I found this one of the most confusing parts of the Qt Model/View
architecture. Good luck.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the PyQt