[PyQt] QTreeView and sorting

Reinaldo de Carvalho reinaldoc at gmail.com
Wed Nov 17 16:51:33 GMT 2010

On Wed, Nov 17, 2010 at 1:42 PM, dizou <di_zou at yahoo.com> wrote:
> I am using a QTreeView and I have sorting enabled. Sorting works great, but I
> want one column to be sorted a specific way that isn't how Qt does it by
> default. I took a look at QSortFilterProxyModel, but this class looks more
> like a way to sort and filter data before the data is displayed in the
> treeview. I am looking to sort the data a specific way after the data is
> already in the tree view and after the user requests it to be sorted that
> way. How would I do this?

You need change (virtually) the values at reimplement QListViewItem
key(), two examples:

class QListViewItemQueueSorted(QListViewItem):
  def __init__(self, *args):
    QListViewItem.__init__(self, *args)

  def key(self, col, asc):
    if col == 0:
        # order email by domain
        text = self.text(col).latin1()
        # have't @ first (add 0 at left)
        if text.find("@") == -1:
            return "0%s" % text
        # change domain to begin of string
            textList = text.split("@")
            return "%s@%s" % (textList[1], textList[0])
    elif col == 1:
        # inserting zero's at left to have a 'number column sorting'
fixing 20 caracters.
        countText = self.text(col).latin1()
        if countText is not None and countText.find("/") != -1:
            countList = countText.split("/")
            return "%s%s/%s%s" % ("0" * (20 - len(countList[1])),
countList[1], "0" * (20 - len(countList[0])), countList[0])
            return self.text(col)
        return self.text(col)

Reinaldo de Carvalho

"While not fully understand a software, don't try to adapt this
software to the way you work, but rather yourself to the way the
software works" (myself)

More information about the PyQt mailing list