Is it possible to sort numbers in a QTreeWidget column?

杀马特。学长 韩版系。学妹 提交于 2019-12-04 05:49:51

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

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)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!