I am trying to implement a table that is sortable on more than one column. Qt’s QSortFilterProxyModel only supports sorting on one column (at least in Qt 4.6.2).
I’ve found this solution by dimkanovikov on github, but it lacks dynamic updating on added rows. What I mean by this, is that the model is changed and the beginInsertRows(), beginRemoveRows(), their corresponding end..-methods and the dataChanged() signals are emitted. Ideally I would like to only these rows to be updated, but the model should at least react to such changes.
There’s another FAQ item on Qt’s site that sorts a QTableWidget, but it lacks dynamic updating, too.
I am new to Qt and I’d like to get some pointers on how I should go about this.
There’s one slightly inelegant solution, that is always used to sort multiple columns.
You have to subclass
QSortFilterProxyModeland reimplementbool lessThan(const QModelIndex &rLeft, const QModelIndex &rRight) const. Instead of only comparing between the two given indices, check all the columns:Then you can call
sort(0)on yourQSortFilterProxyModelsubclass and it will sort all the columns. Also don’t forget to callsetDynamicSortFilter(true)when you want the sorted rows to be dynamically resorted when the model data changes.To support sorting on arbitrary columns in ascending or descending order, you would have to keep this info in a
QListand compare accordingly whenlessThanis called. In the list you would have the columns in order of their priority and do the comparisons in the same order. You should also sort the other “inactive” columns in some predefined order, otherwise they will not be sorted by default.