think nice things
think nice things

Reputation: 4665

Default sort order in QTableView when used with QSortFilterProxyModel

I'm using a custom QSortFilterProxyModel to sort and filter a custom QAbstractTableModel which is displayed in a QTableView.

I've set up sorting and filtering and everything works as expected.

Now I'd like some columns sorted by default ascending and some descending. With "by default" I mean if the column header is clicked the first time this should be the default sort order (and as I've said it differs from column to column).

I could do this by implementing it in my custom QAbstractTableModel depending on the column but then the sort indicator which is shown in the column header wouldn't match the sort order for some columns.

I guess that setting the default sort order should be probably done in QTableView but I didn't find out how.

Any help would be much appreciated.

Upvotes: 3

Views: 4376

Answers (1)

peppe
peppe

Reputation: 22826

To set the sorting that a view does when you click on a header section for the first time you can override headerData for your model, and honour the Qt::InitialSortOrderRole role:

QVariant MyModel::headerData(int section, Qt::Orientation orientation, 
                             int role) const 
{
    if (role == Qt::InitialSortOrderRole)
        return Qt::DescendingOrder; // or maybe Ascending

    return QSqlTableModel::headerData(section, orientation, role);
}

Don't forget to call the parent headerData() method, it does not have to be the QSqlTableModel it depends on which model you extended.

Upvotes: 5

Related Questions