c++ - 格式化 QTableView 显示的日期/时间值

标签 c++ qt c++11 qt5 c++14

我正在使用 QTableView通过模型显示数据库表。其中一个表列有一个时间戳,实际上之前在那里存储了一个 QDateTime。

有没有什么方法可以在呈现时格式化时间戳值?我在想类似 QDateTime("yyyy-MM-dd hh:mm:ss.zzz") 的 .toString。

最佳答案

可以在 this 中按您希望的格式返回日期QAbstractItemModel 的虚方法:

QVariant QAbstractItemModel::data(const QModelIndex &item, int role = Qt::DisplayRole) const;

您必须从 QSqlTableModel 继承您自己的模型并覆盖此方法。代码应该是这样的:

QVariant MySubclassedMode::data(const QModelIndex& item, int role = Qt::DisplayRole) const{

    if(role == Qt::DisplayRole && itemBelongsTodateTimeColumn(item)){

        QDateTime* dateTime = retrieveDateTimeObjectForModelIndex(item);
        return QVariant(dateTime.toString("d MMM YYYY, h:mm"));
    }

    return QSqlTableModel::data(item, role)
}

这种方法可以让您轻松更改对象在表格 View 中的显示方式。

QDateTime 格式详细信息为 here

关于c++ - 格式化 QTableView 显示的日期/时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40494687/

相关文章:

c++ - Boost::bind 与对象占位符

c++ - 相对于另一个顶级对象定位

c++ - 理解带有循环引用的 Shared_ptr?

c++11 - _mm_free 作为 unique_ptr 的删除器

c++ - `for (auto&& e : a)` 比 `for (auto& e : a)` 更有效吗?

c++ - 创建 3 个子进程并在指定秒数后退出它们

c++ - 使用 alpha 值渲染纹理(贴花)?

c++ - LibCurl Unicode 数据

c++ - 使用 QSqlTableModel 的 QTableView 的数据输入

python - 使用非 Qt 从 Qt QJsonDocument::toBinaryData 读取二进制 Json?