格式化QTableView显示的日期/时间值
format date/time value shown by a QTableView
我正在使用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);
}
}
- 使用C++的日期库读取时间
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 为什么在C++中获取日期和/或时间如此复杂?
- 在 MacOS 上C++:显示日期和时间问题
- 如何将我的每个矢量字符串转换为纪元时间日期
- 将 unix 时间戳转换为人类可读的日期
- 使用霍华德·欣南特的日期库将时间信息添加到year_month_day
- 注册表-获取值(而不是键)上次更改的时间和键创建日期
- 我的C++程序如何访问计算机的日期和时间以打印和使用当前年份?
- 使用 C++将时间戳转换为格式化的日期时间
- C++代码的 C# 日期时间等效项是什么?
- 以毫秒级精度对日期和时间进行操作
- 如何在提升日期时间中创建日期范围?
- 将日期字符串转换为 unix 时间戳
- C 自定义时间日期结构到UTC时期
- 使用SNTP(Windows C )从服务器获取时间/日期
- C 的SNTP客户端的时间/日期
- 将文件名的文件另存为当前时间日期
- 在没有宏的情况下获取编译时间日期和时间
- C++应用程序构建时间/日期保存