linuxqtsortingqtreewidgetqtreewidgetitem

Is it possible to sort 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 sort correctly only strings, so my column is sorted:

1 10 100 2 20 200

but this is not the thing I want! Suggestions?


Solution

  • 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.