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?
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With