views:

563

answers:

2

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?

A: 

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.

dsm
+2  A: 

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.

Emilio