【问题标题】:How to sort and change date format in QTableView如何在 QTableView 中排序和更改日期格式
【发布时间】: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


    【解决方案1】:

    解决方案是将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);
    

    【讨论】:

    • 感谢您的出色解决方案!您能否向我发送一个指向更多详细信息文档的链接,我可以通过一般委托了解更多关于这种可能性的信息?或者可能是其他一些例子
    猜你喜欢
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    相关资源
    最近更新 更多