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

format date/time value shown by a QTableView

本文关键字:时间 日期 QTableView 显示 格式化      更新时间:2023-10-16

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

是否有一些方法来格式化时间戳值在演示时间?我在想类似于QDateTime("yyyy-MM-dd hh:mm:ss.zzz")的。tostring .

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)
}

这个方法可以让你很容易地改变对象在表视图中的显示方式。

QDateTime格式的详细信息在这里

有一个函数,它返回你想要的日期格式。

你可以使用"Qt::DateFormat"不同的标志从下面的链接输入到"tostring",根据你需要的格式。

http://doc.qt.io/qt-5/qt.html DateFormat-enum

函数是:

QString QDateTime::toString(Qt::DateFormat format = Qt::TextDate)

http://doc.qt.io/qt-5/qdatetime.html toString-1

将QString添加到表单元格。

如果你只想要时间:

你有"time()"函数在"QDateTime"

QTime time() const "

也有"tostring"用于"QTime",您可以自定义您想要的时间

QString QTime::toString(const QString &format) const

http://doc.qt.io/qt-5/qtime.html toString

在添加到tableview之前在model中更新Datetime:这是我的胡乱猜测(代码是伪的)。

你可以用" datachchanged "信号来处理这种情况

http://doc.qt.io/qt-5/qabstractitemmodel.html dataChanged

首先连接信号并定义一个插槽来处理它。

连接下面的数据变化信号是原型:

connect(ui->tableView->yourMODEL(),SIGNAL(dataChanged(QModelIndex,QModelIndex)),SLOT(UpdateData(QModelIndex,QModelIndex)));

在你的窗口中定义"UpdateData()"

void YourWIndow::UpdateData(const QModelIndex & indexA, const QModelIndex & indexB)
{
    int columnValue = indexA.column();
    int rowValue = indexA.row();
    if("your Column value is QDATETIME column")
    {
        QSqlRecord record = ui->tableView->model()->record(rowValue);
        QVariant var = record (datefieldcolumn);
        QDateTime dTime = var.toDateTime();

        //Format it in your way.
        //Update your QSqlRecord.
        record.setValue(datefieldcolumn,QVariant(formatedDateTime));
        ui->tableView->model()->setRecord(rowValue,record);
    }
}