Solved How to perform action before and after user edits element in QTableView?
-
I have a
QTableView
and would like to perform certain actions before and after the user edits certain elements in the view.At first I naively introduced the code for these actions in my model's
setData
model, but then the actions are performed in other circumstances, for example when a row is dragged and dropped (since that invokessetData
as well). I am not sure there is a way for me to tell whensetData
is being invoked as a result of manual editing, and when it is invoked because of other events.So, in summary, how can I insert code that is run only before and after the user edits an element in a
QTableView
? Thanks. -
@Rodrigo-B Use a delegate:
#include <QApplication> #include <QStandardItemModel> #include <QStyledItemDelegate> #include <QTableView> #include <QDebug> class Delegate: public QStyledItemDelegate{ public: using QStyledItemDelegate::QStyledItemDelegate; void setEditorData(QWidget *editor, const QModelIndex &index) const{ if(editor->isHidden()){ qDebug() << "before"; } QStyledItemDelegate::setEditorData(editor, index); } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{ QStyledItemDelegate::setModelData(editor, model, index); qDebug() << "after"; } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QTableView w; w.setItemDelegate(new Delegate(&w)); QStandardItemModel model(4, 4); w.setModel(&model); w.show(); return a.exec(); }
-
@Rodrigo-B Use a delegate:
#include <QApplication> #include <QStandardItemModel> #include <QStyledItemDelegate> #include <QTableView> #include <QDebug> class Delegate: public QStyledItemDelegate{ public: using QStyledItemDelegate::QStyledItemDelegate; void setEditorData(QWidget *editor, const QModelIndex &index) const{ if(editor->isHidden()){ qDebug() << "before"; } QStyledItemDelegate::setEditorData(editor, index); } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{ QStyledItemDelegate::setModelData(editor, model, index); qDebug() << "after"; } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QTableView w; w.setItemDelegate(new Delegate(&w)); QStandardItemModel model(4, 4); w.setModel(&model); w.show(); return a.exec(); }
-
Great, thank you!
Can you please tell me why you need to check
editor->isHidden()
? -
@Rodrigo-B When testing my code I verified that setEditorData was called 2 times so to avoid it use that condition.
-
@eyllanesc Thank you!
Does anyone know why this is called twice? It seems like it should be called only once.
-
@Rodrigo-B I would have to check the source code of the class but I am lazy to do so, if you want to understand the cause or check the source code or debug Qt.