c++ - QSortFilterProxyModel 按日期排序

标签 c++ qt sorting qt5 qsortfilterproxymodel

我想按日期对表格进行排序。问题是它们被解释为字符串,因此我的本地日期格式排序错误,例如 26。 9 月16 还要大。 11 月,因为 26 > 16

无论如何,所以我设置了自己的模型并尝试如下:

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::UserRole)
    {
        if(index.column() == 5) // Date
           return QSqlTableModel::data(index, role).toDate();
    }

    if(role == Qt::DisplayRole)
    {
        if(index.column() == 5) // Date
           return QSqlTableModel::data(index.role).toDate().toString("dd MMMM yyyy");
    }
}

我设置了sortRole,如下所示:

proxyModel->setSortRole(Qt::UserRole);

相应的行实际上被调用了,但现在我根本无法对表进行排序。它只是没有回应。相应列处的箭头(表示升序或降序排序)正在发生变化,但数据没有变化。 当然,我将其余部分设置为:

proxyModel->setDynamicSortFilter(true);
proxyModel->setSourceModel(myDBModel);
proxyModel->setFilterKeyColumn(1);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

如果我不设置 sortRole 至少我可以按其他列正确排序。 我在这里做错了什么?我是否必须实现其他功能或其他功能?我浏览了互联网,但我发现的只是对几年前的整数进行排序的问题,而不是日期:(

最佳答案

我是个白痴(事实!)

Qt 已经提供了我需要的一切,这对我来说只是一个愚蠢的错误。确实有两件事:

   if(role == Qt::UserRole)
    {
        if(index.column() == 5)
            return QDate::fromString(QSqlTableModel::data(index, Qt::DisplayRole).toString(), "yyyy-MM-dd"); // 1st Mistake, no correct conversion. I always got QVariant(invalid)
// 1.1 Mistake, also, grab the data from Qt::DisplayRole, not from Qt::UserRole!

        return QSqlTableModel::data(index, Qt::DisplayRole); // 2nd Mistake. Because I didn't add that line I couldn't sort it on any other column anymore. When I finally could sort it on the dates I couldn't on the other columns, then I thought about adding this line et voila!
    }

我想感谢您的友好和快速的答复,但是这次问题出现在椅子和键盘之间。

关于c++ - QSortFilterProxyModel 按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574923/

相关文章:

C++ GoogleTest - 静态成员和链接器错误 LNK 2001

c++ - int 的构造函数中参数的可变数量

c++ - 如何用QToolButton正确管理文本和图标?

macos - Mac OS X 文件关联有效,但文件图标未更改

performance - 我可以使用 Big-O 表示法来比较同一算法的优化和未优化实现的性能吗?

Postgresql函数对字符串中的字符进行排序

c++ - 大于 16 位的线程 block 的配置参数无效

c++ - Boost 中的多读单写锁

C++ 错误 : because the following virtual functions are pure within

javascript - 高级对象排序