如何在QTableView中排序和更改日期格式
How to sort and change date format in QTableView
>我已经在Qt5中实现了QTableView
+QStandardItemModel
。一开始,我根据应用程序设置将日期数据设置为具有日期格式的字符串。例如,它可以是MM/dd/yyyy
等美国格式或欧洲格式dd.MM.yyyy
。数据来自欧洲日期格式的 json 文件。我的第一个实现是这样的:
shared_ptr<QStandardItemModel> _model;
// detect a date string with regex, get the submatches and create a QDate object from it
QDate date(stoi(submatches[3].str()), stoi(submatches[2].str()), stoi(submatches[1].str()));
QModelIndex index = _model->index(rowPos, colPos, QModelIndex());
// depends on the setting, the date can be shown on the table like this
_model->setData(index, QString(date.toString("dd.MM.yyyy"));
// activate the column sorting in the QTableView
ui->tableView->setSortingEnabled(true);
但是,此实现无法正确对日期列进行排序。原因是 QTableView 对列进行排序就像字符串(按日期排序而不是按年份排序(而不是日期条目一样。
我可以通过直接使用 date 对象设置数据来更改实现:
_model->setData(index, date);
按日期排序完美。但是,格式现在始终以dd/MM/yyyy
格式显示。 如何保留此排序功能,但根据日期格式设置更改日期视图?
我读过它可以使用QAbstractTableModel
的自定义子类来实现。如何实现为QTableView
的子类?或者可能像这里一样带有QAbstractItemModel
的子类?我还不是实现和集成Qt5子类的专家。
解决方案是将 QDate 作为数据传递给模型,并使用委托进行设置,如视图中所示:
_model->setData(index, date);
class DateDelegate: public QStyledItemDelegate{
public:
using QStyledItemDelegate::QStyledItemDelegate;
QString displayText(const QVariant &value, const QLocale &locale) const{
return locale.toString(value.toDate(), "dd.MM.yyyy");
}
};
ui->tableView->setItemDelegateForColumn(col_date, new DateDelegate);
相关文章:
- 日期格式为C++
- 如何在QTableView中排序和更改日期格式
- 如何检查日期格式(日/月/年)是否正确C++
- 如何使用put_time()设置日期格式以删除前面的空格和零
- 在 c++ 中验证日期格式
- 使用字符串流设置日期格式
- 日期格式-将日期添加到日期
- 如何在黑莓10中将日期格式转换为字符串
- 提升公历日期格式会产生错误的结果
- Excel 国际日期格式
- 日期格式操作(年/月/日到月/日/年)
- 使用预处理器定义的日期格式
- 将日期格式Www-Mmm-dd hh:mm:ss yyyy转换为c++中的dd hh:mm:ss字符串
- 将字符串设置为日期格式
- 时间刻度到日期格式
- 转换日期格式
- 获取Win32系统日期格式字符串
- 在c++中自定义日期格式
- 如何检查日期格式的有效性(例如,%d/%m/%Y-%H:% m:%S)
- 以字符串形式返回整数值以进行日期格式设置