Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default sort order in QTableView when used with QSortFilterProxyModel

Tags:

qt5

pyqt5

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.

like image 813
think nice things Avatar asked Jul 02 '26 21:07

think nice things


1 Answers

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.

like image 87
peppe Avatar answered Jul 05 '26 11:07

peppe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!