1

I want to use the PyQt equivalent of the following SQL statement in my model/view-based PyQt application:

SELECT * FROM table ORDER BY foo, bar

How do I sort by multiple columns in a QSqlTableModel, especially since setSort() accepts a single column argument?

1 Answers1

2

It seems there's an alternative to setSort(), called setFilter(). From the PyQt docs:

QSqlTableModel.setFilter (self, QString filter)

Sets the current filter to filter.

The filter is a SQL WHERE clause without the keyword WHERE (for example, name='Josephine').

Ergo, this solves the problem:

fooModel.setFilter("never_zero != 0 ORDER BY foo, bar")

where the never_zero field is (surprise, surprise) never zero.

  • 1
    This is more like cheating and might be misleading. You usually don't expect sorting query in filters. `QSqlTableModel` is rather limited when you need complex queries. `QSqlQueryModel` should be the option. If you need write access, you can subclass it to provide appropriate methods. Or if your dataset is not that big, you might consider putting a custom `QSortFilterProxyModel` in between. It needs to be custom, since original `QSortFilterProxyModel` also expects single column for sorting, but it is rather easy to subclass and provide your own sorting implementation. – Avaris Mar 05 '12 at 04:48