c++ - Qt 模型/ View 委托(delegate) : How to simply translate text data?

标签 c++ windows qt

我使用 QSqlTableModel 作为数据源并使用 QTableView 来显示数据。 我还使用 QDataWidgetMapper 以单独的形式编辑数据。

我想要做的就是将日期/时间字符串从数据库中的一种格式 (2011-07-09T18:21:49) 转换为另一种格式以显示在表中 (18:21) 以及另一种格式编辑映射(09.07.2011 18:21:49)

我认为 ItemDelegate 是正确的方式,但我不想更改绘画等......我该如何正确地做?

最佳答案

好的,我认为这可能是正确的方法(中间数据模型), 但现在我使用了 QItemDelegate。 我执行了以下操作并且有效:

class DateTimeDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit DateTimeDelegate(QObject *parent = 0);

void setEditorData(QWidget *editor,
                   const QModelIndex &index) const;

void setModelData(QWidget *editor,
                  QAbstractItemModel *model,
                  const QModelIndex &index) const;

void paint(QPainter *painter, const QStyleOptionViewItem &option,
           const QModelIndex &index) const;

signals:

public slots:

};

实现:

void DateTimeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if(index.column() == 1 || index.column() == 2)  {
        if (editor->property("text").isValid()) {
            QDateTime dt = QDateTime::fromString(index.data().toString(), Qt::ISODate);
            editor->setProperty("text", dt.toString("dd.MM.yyyy hh:mm"));
        }
    } else {
        QItemDelegate::setEditorData(editor, index);
    }
}

void DateTimeDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
           const QModelIndex &index) const
{
    QDateTime dt = QDateTime::fromString(index.data().toString(), Qt::ISODate);


    QString time;
    if(dt.date() == QDate::currentDate())
        time = dt.toString("hh:mm");
    else
        time = dt.toString("dd.MM.");

    painter->save();
    painter->setClipRect(option.rect);

    drawBackground(painter, option, index);
    drawDisplay(painter, option, option.rect, time);
    drawFocus(painter, option, option.rect);

    painter->restore();
}   

关于c++ - Qt 模型/ View 委托(delegate) : How to simply translate text data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6636202/

相关文章:

c++ - 迭代器作为映射值出错

c++ - Antlr4 语法意外错误(C++ 目标)

windows - Windows 10 上的 Visual Studio 2010 x64 编译器

php - 为什么大数组索引没有正确存储?

windows - 从 Ubuntu 9.10 访问 Windows 上的 svn 存储库

android - 使用openCV库时necessitas中的错误

c++ - CryptDecrypt() 无法解密某些 block C++

c++ - 名称、论文、书籍未在此范围内声明非成员函数 C++

c++ - 从C++中的共享库调用指向列表的静态指针

c++ - 将字符串保存到重载的括号中而不更改对象的字段