Can I sort the numbers in a QTreeWidget column?

I have a QTreeWidget with a column filled with some numbers, how can I sort them?

If I use setSortingEnabled (true); I can only sort rows correctly, so my column is sorted:

1 10 100 2 20 200

but this is not what i want! Suggestions?

+6
sorting linux qt qtreewidgetitem qtreewidget
source share
4 answers

You can sort the override of the <operator and changing the sort conditions as follows.

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, he ignores the real case when faced with lowercase fields.

+7
source share

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() 
+4
source share

The best way I've found is to use a try block to search for 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) 
+3
source share

sorting numbers by numerical value, but strings sort the opposite way (i.e. "19999" < "2" ).

In particular, strings are compared character by character from left to right until one or the other characters are different, after which the comparison stops. For example, 19 and 121 will be compared as follows:

 "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 a numerical value and then sort them. In addition, you can implement your own sorting algorithm that reads numbers correctly.

0
source share

All Articles