There's one slightly inelegant solution, that is always used to sort multiple columns.
You have to subclass QSortFilterProxyModel and reimplement bool lessThan(const QModelIndex &rLeft, const QModelIndex &rRight) const. Instead of only comparing between the two given indices, check all the columns:
int const left_row = rLeft.row();
int const right_row = rRight.row();
int const num_columns = sourceModel()->columnCount();
for(int compared_column = rLeft.column(); compared_column<num_columns; ++compared_column) {
QModelIndex const left_idx = sourceModel()->index(left_row, compared_column, QModelIndex());
QModelIndex const right_idx = sourceModel()->index(right_row, compared_column, QModelIndex());
QString const leftData = sourceModel()->data(left_idx).toString();
QString const rightData = sourceModel()->data(right_idx).toString();
int const compare = QString::localeAwareCompare(leftData, rightData);
if(compare!=0) {
return compare<0;
}
}
return false;
Then you can call sort(0) on your QSortFilterProxyModel subclass and it will sort all the columns. Also don't forget to call setDynamicSortFilter(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 QList and compare accordingly when lessThan is 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.
void QAbstractItemModel::sort ( int column, Qt::SortOrder order = Qt::AscendingOrder )and is probably more complicated to implement then what I did. – kossmoboleat Jun 27 '12 at 8:28