JuanDeLosMuertos
JuanDeLosMuertos

Reputation: 4620

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?

Upvotes: 8

Views: 9865

Answers (5)

Soeren Zimmermann
Soeren Zimmermann

Reputation: 159

You could also insert the displayed text as integer:

for ( int i = 0; i < 1000; ++i )
{
   auto pTreeWidgetItem{ new QTreeWidgetItem( pTreeWidget ) };
   pTreeWidgetItem->setData( 0, Qt::DisplayRole, i + 1 );
}

In this case, the item will recognize the integer and will sort it correctly. The text displayed still is the number itself.

Upvotes: 0

Alen
Alen

Reputation: 41

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)

Upvotes: 4

PedroMorgan
PedroMorgan

Reputation: 926

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()

Upvotes: 6

Emilio
Emilio

Reputation: 4031

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.

Upvotes: 12

dsm
dsm

Reputation: 10395

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.

Upvotes: -1

Related Questions