Home > Enterprise >  Can't sort model by QDateTime with using QSortFilterProxyModel sort by role
Can't sort model by QDateTime with using QSortFilterProxyModel sort by role

Time:10-02

I am stuck with simple problem but I can't figure it out why my model is not sorted. I have SimpleModel class that inherits from QAbstractListModel and I want to sort it by DateTime role.

ccc

This is how I am setting the Proxy in my main.cpp:

SimpleModel m;
ProxyModel proxyModel;
proxyModel.setSourceModel(&m);
proxyModel.setSortRole(SimpleModel::SimpleRoles::DateTimeRole);
engine.rootContext()->setContextProperty("simpleModel", &proxyModel);

My Items in the SimpleModel are objects from SimpleItem class which has only Name and DateTime. This is my SimpleModel data method:

QVariant SimpleModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid()) {
        return QVariant();
    }

    auto simpleItem = static_cast<SimpleItem*>(index.internalPointer());
    if (!simpleItem) {
        return QVariant();
    }

    if(role == NameRole) {
        return simpleItem->name();
    }
    //This is used for displaying in QML
    else if(role == DateRole) {
        return simpleItem->dateTime().toString("yyyy-MM-dd");
    }
    // This is used for dsiplaying in QML too
    else if(role == TimeRole) {
        return simpleItem->dateTime().toString("hh:mm");
    }
    // This Role is only used for sorting
    else if(role == DateTimeRole) {
        return simpleItem->dateTime();
    }

    return QVariant();
}

And in my ProxyModel that inherits from QSortFilterProxyModel class I have implemented lessThan() methood but it never gets called:

bool ProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
    qDebug() << "called lessThan()";
    QVariant leftData = sourceModel()->data(source_left);
    QVariant rightData = sourceModel()->data(source_right);

    if (leftData.userType() == QMetaType::QDateTime)
            return leftData.toDateTime() < rightData.toDateTime();

    return false;
}

What I am doing wrong or do you have any idea that I can try? If you need more code I will update. Thanks in advance.

CodePudding user response:

as you say

it works after calling proxyModel.sort(0, Qt::DescendingOrder); after setSortRole

  • Related