The user can modify the data using the delegate, so itβs possible:
#ifndef ITEMDELEGATE_H #define ITEMDELEGATE_H #include <QItemDelegate> class ItemDelegate : public QItemDelegate { Q_OBJECT public: explicit ItemDelegate(QObject *parent = 0); protected: QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget * editor, const QModelIndex & index) const; void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const; void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const; signals: void dataChanged(QString oldValue,QString newValue) const; public slots: private: mutable QString old;//we want change member data in const method }; #endif // ITEMDELEGATE_H
As you can see, many const
methods are default, so I did some tricks (e.g. mutable
) to avoid problems. Also in my edited answer I do not store the old data in UserRole+1
, everything is done with the old mutable
variable.
castes:
#include "itemdelegate.h" #include <QLineEdit> #include <QDebug> ItemDelegate::ItemDelegate(QObject *parent) : QItemDelegate(parent) { } QWidget *ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QLineEdit *editor = new QLineEdit(parent); return editor; } void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { old = index.model()->data(index, Qt::EditRole).toString();//store old data QLineEdit *line = qobject_cast<QLineEdit*>(editor); line->setText(old); } void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index)const { QLineEdit *line = static_cast<QLineEdit*>(editor); QString data = line->text(); emit dataChanged(old, line->text()); model->setData(index, data); } void ItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); }
Using:
ItemDelegate * del = new ItemDelegate; connect(del,&ItemDelegate::dataChanged,[=](QString oldValue,QString newValue) { qDebug() << "old" << oldValue<< "new" <<newValue ; }); ui->tableView->setItemDelegate(del);
I tested it and it works. He will work with different models. QTableView
is used by default lineEdit
as a delegate, so the user does not see any changes in the view.
I used C++11
( CONFIG += c++11
to .pro
file) and the new syntax for signals and slots , but of course you can use the old syntax if you want.