qtableviewqsortfilterproxymodel

Applying a persistent filter to a periodically updated qtableview in python


I've a custom model of a QtableView displaying data that I want to filter out on a column. The Qtableview function updateAccountTable is refreshed periodically from a timer to show real-time data. I've put a QlineEdit to seize my filter value and I do apply my custom QSortFilterProxyModel on this. I can see the data is filtered in the Qtableview, until the next refresh where the list is again unfiltered. This come obviously from the signal textChanged of the Qline Edit which is not persistent but I do not see how to have my QSortFilterProxyModel be persistent after the Qtableview refresh Any idea on how to do that ? Cheers Stephane

Part of my code is :

    # AccountTableView sorting overide function
    class mysortingproxy(QSortFilterProxyModel):
            def __init__(self, parent=None):
                super(mysortingproxy, self).__init__(parent)
        
            def lessThan(self, left: QModelIndex, right: QModelIndex) -> bool:
                leftData = self.sourceModel().data(left, Qt.UserRole)
                rightData = self.sourceModel().data(right, Qt.UserRole)
                return leftData < rightData
        
        
    class MainUi(QMainWindow):
           # snip...
    
            def updateAccountTable(self):
                # Account table
                self.accountTableModel = AccountTableModel(self.data, self.scalping)
                proxyModel = mysortingproxy()        # if not sorting override : proxyModel = QSortFilterProxyModel()
                proxyModel.setFilterKeyColumn(0)  # first column
                proxyModel.setSourceModel(self.accountTableModel)
                self.tableView_Account.setModel(proxyModel)
                self.tableView_Account.setSortingEnabled(True)
                self.tableView_Account.verticalHeader().setVisible(False)
                # filter proxy model
                self.lineEdit_Find.textChanged.connect(proxyModel.setFilterRegExp)

Solution

  • found it! This actually only required to add the reading of the filter field each time before displaying my data and then apply the filter again The code became

        def updateAccountTable(self):
        # Account table
        self.accountTableModel = AccountTableModel(self.data, self.scalping)
        proxyModel = mysortingproxy()        # if not sorting override : proxyModel = QSortFilterProxyModel()
        proxyModel.setFilterKeyColumn(0)  # first column
        proxyModel.setSourceModel(self.accountTableModel)
        self.tableView_Account.setModel(proxyModel)
        self.tableView_Account.setSortingEnabled(True)
        self.tableView_Account.verticalHeader().setVisible(False)
        # filter proxy model
        self.lineEdit_Find.textChanged.connect(proxyModel.setFilterRegExp)
        self.crypto_find = self.lineEdit_Find.text()
        proxyModel.setFilterRegExp(self.crypto_find.upper())