PDA

View Full Version : PyQt4: Multicolumn filter in tableView based on SQlite table - how?



robs23
7th November 2016, 13:29
I've been pounding my head over this for a whole weekend and can't seem to find the solution. I'm trying to build a filter form in PyQt4 that would filter a tableView with user's string. As a source of data is SQLite table, I use QSqlQueryModel as tableView's model. In order to be able to sort/filter, I use QSortFilterProxyModel in-between tableView and QSqlQueryModel. Unfortunately, QSortFilterProxyModel allows me only to filter based on single column while I'd like to filter on 2 columns at the same time. I found this site where fellow programmer is subclassing QSortFilterProxyModel to achieve multicolumn filtering. He's redefining its filterAcceptsRow method to accept several columns. Now, the thing is it uses data model's "row" method which is not present in QSqlQueryModel. I think I'd have to subclass QSqlQueryModel and add row method though I'm not sure what it's supposed to do.

Here's whole code behind custom filterAcceptsRow (with author's comments, I hope he wouldn't mind that):


def filterAcceptsRow(self, row_num, parent):
"""
model refers to our source model which is subclassed from
QAbstractTableModel. It has a method called row(row_num)
that returns the row in the table as a python list.

filterString is a string to filter against which has
been previously set. For illustration purposes we
don't bother with regular expression support, but
this could easily be added.

filterColumns is a list of columns to test against,
it should have the form [3, 4] to test against columns
3 and 4.
"""
model = self.sourceModel() # the underlying model,
# implmented as a python array
row = model.row(row_num)
tests = [self.filterString in row[col]
for col in self.filterColumns]

return True in tests # accepts row if any column
# contains filterString

Any help is very welcome as I'm going nuts.