How can I get previous data of QTableWidgetItem?
Solved
General and Desktop
-
@Aaron-Kim
Since there does not appear to be somebeforeItemChanged()
signal, unless you know just what will cause the item changed in your code (e.g. can you look at the model'ssetData()
perhaps?) you are on your own. You would have to have stored up the data's previous value yourself somewhere. I don't think you're supposed to try to get back at old data from the view, I think you're supposed to do it from the model side. -
@Aaron-Kim
You need to save it somewhere.Something like this:
.h fileprivate: vector<vector<QString> > arr;
.cpp constructor:
for (int i = 0; i < 10; i++) { vector<QString> t; for (int j = 0; j < 5; j++) { t.push_back(QString("%1, %2").arg(QString::number(i), QString::number(j))); } arr.push_back(t); } ui->tableWidget->setColumnCount(5); ui->tableWidget->setRowCount(arr.size()); for (int i = 0; i < 10; i++) { for (int j = 0; j < 5; j++) { ui->tableWidget->setItem(i, j, new QTableWidgetItem(arr[i][j])); } } connect(ui->tableWidget, &QTableWidget::itemChanged, this, [=](QTableWidgetItem *item) { int row = item->row(); int column = item->column(); qDebug() << "previous value: " << this->arr[row][column]; qDebug() << "new value: " << item->text(); this->arr[row][column] = item->text(); });
-
Requires Qt >= 5.11
QObject::connect(tableWidget->model(),&QAbstractItemModel::dataChanged,[=](const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles){ if(!roles.isEmpty() && !roles.contains(Qt::EditRole)) return; for(int i=topLeft.row();i<=bottomRight.row();++i){ for(int j=topLeft.column();j<=bottomRight.column();++j){ const QModelIndex currIdx = topLeft.model()->index(i,j,topLeft.parent()); qDebug() << i << ";" << j << " Previous Value: " << currIdx.data(Qt::UserRole); tableWidget->model()->setData(currIdx, currIdx.data(Qt::EditRole), Qt::UserRole); } } });