diff --git a/src/gui/itemmodels/qstandarditemmodel.cpp b/src/gui/itemmodels/qstandarditemmodel.cpp index 2998808b54..9bdc22b49e 100644 --- a/src/gui/itemmodels/qstandarditemmodel.cpp +++ b/src/gui/itemmodels/qstandarditemmodel.cpp @@ -138,10 +138,19 @@ void QStandardItemPrivate::setChild(int row, int column, QStandardItem *item, return; } } + + // setting the model to nullptr invalidates the persistent index which we want to avoid + if (!item && oldItem) + oldItem->d_func()->setModel(nullptr); + + children.replace(index, item); + + // since now indexFromItem() does no longer return a valid index, the persistent index + // will not be invalidated anymore if (oldItem) oldItem->d_func()->setModel(nullptr); delete oldItem; - children.replace(index, item); + if (item) item->d_func()->lastKnownIndex = index; diff --git a/tests/auto/gui/itemmodels/qstandarditemmodel/tst_qstandarditemmodel.cpp b/tests/auto/gui/itemmodels/qstandarditemmodel/tst_qstandarditemmodel.cpp index bc8bc38da6..032f17c0a7 100644 --- a/tests/auto/gui/itemmodels/qstandarditemmodel/tst_qstandarditemmodel.cpp +++ b/tests/auto/gui/itemmodels/qstandarditemmodel/tst_qstandarditemmodel.cpp @@ -131,6 +131,7 @@ private slots: void supportedDragDropActions(); void taskQTBUG_45114_setItemData(); + void setItemPersistentIndex(); private: QStandardItemModel *m_model; @@ -1811,5 +1812,26 @@ void tst_QStandardItemModel::taskQTBUG_45114_setItemData() QVERIFY(!itemRoles.keys().contains(Qt::UserRole + 3)); } +void tst_QStandardItemModel::setItemPersistentIndex() +{ + QPersistentModelIndex persistentIndex; + // setItem on an already existing item should not destroy the persistent index + QStandardItemModel m; + persistentIndex = m.index(0, 0); + QVERIFY(!persistentIndex.isValid()); + + m.setItem(0, 0, new QStandardItem); + persistentIndex = m.index(0, 0); + QVERIFY(persistentIndex.isValid()); + QCOMPARE(persistentIndex.row(), 0); + QCOMPARE(persistentIndex.column(), 0); + + m.setItem(0, 0, new QStandardItem); + QVERIFY(persistentIndex.isValid()); + + m.setItem(0, 0, nullptr); + QVERIFY(!persistentIndex.isValid()); +} + QTEST_MAIN(tst_QStandardItemModel) #include "tst_qstandarditemmodel.moc"