To add the sort and filter functionalities you can create a QSortFilterProxyModel object.
This new object will be interposed between the model and the view.
QSortFilterProxyModel works on the indexes so it will allow adding those functionalities without any modification or duplication of the data at the source.
Let me add a string column to the original data of the Martin’s tutorial:
data = pd.DataFrame([
[1, 9, 2, "door"],
[1, 0, -1, "dog"],
[3, 5, 2, "duck"],
[3, 3, 2, "dog"],
[5, 8, 9, "air"],
], columns = ['A', 'B', 'C', 'D'], index=['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Row 5'])
The code was:
self.model = TableModel(data)
self.table.setModel(self.model)
For sorting it would become:
self.model = TableModel(data)
self.proxyModel = QSortFilterProxyModel()
self.proxyModel.setSourceModel(self.model)
self.table.setSortingEnabled(True)
self.table.setModel(self.proxyModel)
The method setSortingEnabled(True) must be called because sorting is disabled by default.
While for filtering it would become:
self.model = TableModel(data)
self.proxyModel = QSortFilterProxyModel()
self.proxyModel.setSourceModel(self.model)
self.proxyModel.setFilterKeyColumn(3)
self.proxyModel.setFilterFixedString("dog")
#self.proxyModel.setFilterWildcard("do")
#self.proxyModel.setFilterRegExp(QRegExp("do.*"))
self.table.setModel(self.proxyModel)
The method setFilterKeyColumn() allows you to select the column for the filtering (column indexes start from 0).
For custom sorting you can reimplement the sort() method in the QAbstractTableModel class.
For custom filtering you can reimplement the filterAcceptsRow() or the filterAcceptsColumn() in the QSortFilterProxyModel class.