Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 958
Giancarlo Avatar asked Dec 12 '08 16:12

Giancarlo


2 Answers

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.

like image 182
Emilio Avatar answered Sep 19 '22 11:09

Emilio


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()
like image 36
PedroMorgan Avatar answered Sep 19 '22 11:09

PedroMorgan