Filtering out model items based on item data

69 Views Asked by At

I have a QStandardItemModel from which I need to use a subset. The filtering is done not by name but item.data() which is a dict. I can get the text excluded but the items are still populated in the view. How can I exclude the items completely from the view? Is the approach correct?

empty

class WatchlistProxyModel(QSortFilterProxyModel):
    def __init__(self, parent=None):
        QSortFilterProxyModel.__init__(self, parent)

    def data(self, index, role):
        if role in (Qt.DisplayRole,):
            data = self.sourceModel().itemFromIndex(self.mapToSource(index)).data()

            if data is not None:
                if data['source'] != '$WATCHLIST$':
                    return

        return QSortFilterProxyModel.data(self, index, role)
1

There are 1 best solutions below

0
misantroop On

Went with the solution suggested by G.M., implementing data() was not necessary:

class WatchlistProxyModel(QSortFilterProxyModel):
    def __init__(self, parent=None):
        QSortFilterProxyModel.__init__(self, parent)

    
    def filterAcceptsRow(self, source_row, source_parent):
        index = self.sourceModel().index(source_row, 0, source_parent)
        data = self.sourceModel().itemFromIndex(index).data()

        if data is not None:
            if data['source'] == '$WATCHLIST$':
                return False

        return QSortFilterProxyModel.filterAcceptsRow(self, source_row, source_parent)