mfessenden
mfessenden

Reputation: 608

Sort a QTreeWidgetItem by a data value?

Is it possible to sort a PyQt QTreeWidget by a QTreeWidgetItem's data column?

For example, I've got a list of directories I want to sort by size on disk displaying in the QTreeWidget, but instead of displaying the results (in bytes) I use a method to convert the directory size to megabytes/gigabytes, but still be able to sort the items by the actual value, which I've stored in the QTreeWidgetItem's data slot.

Upvotes: 1

Views: 4196

Answers (1)

Eric Hulser
Eric Hulser

Reputation: 4022

Yea, I've run into this a lot. I've always thought that theoretically doing something like:

item = QTreeWidgetItem()
item.setData(0, Qt.EditRole, QVariant(1024))
item.setData(0, Qt.DisplayRole, '1 Kb')

SHOULD work...unfortunately it does not. The only real way to get it to work is to subclass the QTreeWidgetItem and either store your sort information in its own way, or use the Qt.UserRole vs. EditRole or DisplayRole:

class MyTreeWidgetItem(QTreeWidgetItem):
    def __lt__( self, other ):
        if ( not isinstance(other, MyTreeWidgetItem) ):
            return super(MyTreeWidgetItem, self).__lt__(other)

        tree = self.treeWidget()
        if ( not tree ):
            column = 0
        else:
            column = tree.sortColumn()

        return self.sortData(column) < other.sortData(column)

    def __init__( self, *args ):
        super(MyTreeWidgetItem, self).__init__(*args)
        self._sortData = {}

    def sortData( self, column ):
        return self._sortData.get(column, self.text(column))

    def setSortData( self, column, data ):
        self._sortData[column] = data

So, using it in this case would be similar to before, but actually allow for sorting via custom data:

item = MyTreeWidgetItem()
item.setSortData(0, 1024)
item.setText(0, '1 kb')01

Upvotes: 7

Related Questions