mc360pro mc360pro - 1 year ago 146
C++ Question

QSortFilterProxyModel sort based on two sort roles?

In my project, I have a model displayed in a treeview. I used QSortFilterProxyModel to sort the model based on an ID set in Qt::UserRole+1. This divides my list by "type" (as you can tell by the icons used):

enter image description here

However I also want each "type" to be sorted alphabetically. I initially tried to sort things alphabetically FIRST and THEN sort it by type to see if it would rearrange things to work properly, but it stays the same. Is there any way to tell my program to sort with two sort roles AND determine which one "goes first?"


Answer Source

Since my duplicate urls were nuked, here goes the working example right from the official example after some minor adjustment:

class MySortFilterProxyModel Q_DECL_FINAL : public QSortFilterProxyModel

    MySortFilterProxyModel(QObject *parent)
        : QSortFilterProxyModel(parent)

    bool lessThan(const QModelIndex &left, const QModelIndex &right) const Q_DECL_OVERRIDE
        QVariant leftData = sourceModel()->data(left);
        QVariant rightData = sourceModel()->data(right);
        // Do custom logic in here, e.g.:
        return QString::localeAwareCompare(leftData.toString(), rightData.toString()) < 0;

Then, this custom class would be used normally in place of the original as a drop-in replacement. That is it!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download