问题
I have a QTreeWidget with a column filled with some numbers, how can I sort them?
If I use setSortingEnabled(true); I can sort correctly only strings, so my column is sorted:
1 10 100 2 20 200
but this is not the thing I want! Suggestions?
回答1:
You can sort overriding the < operator and changing sort condiction like this.
class TreeWidgetItem : public QTreeWidgetItem {
public:
TreeWidgetItem(QTreeWidget* parent):QTreeWidgetItem(parent){}
private:
bool operator<(const QTreeWidgetItem &other)const {
int column = treeWidget()->sortColumn();
return text(column).toLower() < other.text(column).toLower();
}
};
In this example it ignore the real case, confronting fields in lowercase mode.
回答2:
Here's a pyQt implementation using __lt__
class TreeWidgetItem(QtGui.QTreeWidgetItem):
def __init__(self, parent=None):
QtGui.QTreeWidgetItem.__init__(self, parent)
def __lt__(self, otherItem):
column = self.treeWidget().sortColumn()
return self.text(column).toLower() < otherItem.text(column).toLower()
回答3:
The best way i found is to use a try block to find numbers
class TreeWidgetItem( QtGui.QTreeWidgetItem ):
def __init__(self, parent=None):
QtGui.QTreeWidgetItem.__init__(self, parent)
def __lt__(self, otherItem):
column = self.treeWidget().sortColumn()
try:
return float( self.text(column) ) > float( otherItem.text(column) )
except ValueError:
return self.text(column) > otherItem.text(column)
回答4:
numbers sort by numeric value, but strings sort the opposite way (i.e. "19999" < "2"
).
More specifically, strings are compared character by character from left to right until one one or the other characters differ, at which point the comparision is stopped. For instance, 19
and 121
will be compared like this:
"19"[0] != "121"[0] ? // no
"19"[1] != "121"[1] ? // yes
'9' > '2' ? // yes
return some value that indicates "19" greater than "121";
To sort them correctly you will need to convert them to the numeric value and then sort them. Other than that you could implement your own sorting algorithm that reads numbers the correct way.
来源:https://stackoverflow.com/questions/363200/is-it-possible-to-sort-numbers-in-a-qtreewidget-column