【发布时间】:2020-07-01 14:32:13
【问题描述】:
我已经在 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 对列进行排序就像一个字符串(按天排序而不是按年份排序)而不是日期条目。
我可以通过直接用日期对象设置数据来改变实现:
_model->setData(index, date);
按日期完美排序。但是,格式现在总是以dd/MM/yyyy 格式显示。
如何保留此排序功能,但更改日期视图取决于日期格式设置?
我读到它可以使用QAbstractTableModel 的自定义子类来实现。实现为QTableView 的子类怎么样?或者可能是QAbstractItemModel 的子类,例如here?我还不是实现和集成 Qt5 子类的专家。
【问题讨论】:
标签: c++ qt5 c++14 qtableview