格式化由QTableView显示的日期/时间值
我正在使用 QTableView 通过模型显示数据库表.表格中的一列有时间戳记,实际上是在此之前存储了一个QDateTime.
I´m using a QTableView to show a database table via model. One of the table columns have a timestamp, acctually a QDateTime was stored there before.
是否有某种方法可以在演示时格式化时间戳记值?我在考虑类似 QDateTime("yyyy-MM-dd hh:mm:ss.zzz")
的.toString.
Is there some way to format the timestamp value at presentation time? I was thinking in something like the .toString of a QDateTime("yyyy-MM-dd hh:mm:ss.zzz")
.
It is possible to return date formatted as you wish in this virtual method of QAbstractItemModel
:
QVariant QAbstractItemModel::data(const QModelIndex &item, int role = Qt::DisplayRole) const;
您必须从QSqlTableModel继承您自己的模型,并重写此方法.代码段如下:
You'll have to subclass your own model from QSqlTableModel and override this method. Code shold be something as follows:
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)
}
这种方法将使您轻松更改对象在表格视图中的显示方式.
This approach will allow you to easily change how the object will be displayed in table view.
QDateTime格式详细信息位于此处
QDateTime formatting details are here