如何在QTableView中排序和更改日期格式

How to sort and change date format in QTableView

本文关键字:日期 格式 排序 QTableView      更新时间:2023-10-16

>我已经在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);