Miso
Miso

Reputation: 179

QSortFilterProxyModel and row numbers

I'm using some tableview with related model extended with QSortFilterProxyModel because of sorting and/or filtering. Everything works fine except row numbers (I mean vertical header). Using this code:

def headerData(self, section, orientation, role):
    if role == QtCore.Qt.DisplayRole:
        if orientation == QtCore.Qt.Horizontal:
            return self.__header[section]
        elif orientation == QtCore.Qt.Vertical:
            return section + 1

fixed row number is assigned to each row. And this causes problems when sorting/filtering. I figured out one solution: override default filtering and sorting methods and put some additional parameter (row number) into data and rewrite it during each sorting or filtering.

Question: is there any other solution for this? Some method which shows me real item position after sorting/filtering manipulation?

Upvotes: 1

Views: 1872

Answers (1)

Avaris
Avaris

Reputation: 36715

A simple subclass of QSortFilterProxyModel with custom headerData would do that:

class MyProxy(QtGui.QSortFilterProxyModel):
    def headerData(self, section, orientation, role):
        # if display role of vertical headers
        if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
            # return the actual row number
            return section + 1
        # for other cases, rely on the base implementation
        return super(MyProxy, self).headerData(section, orientation, role)

Upvotes: 5

Related Questions