我使用 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/