QComboBox: make setModel reset the root model index

When changing models it makes no sense to keep the old root model index,
pointing into a possibly deleted model. Reset it to the root
of the new model is the best line of action.

[ChangeLog][QtWidgets][QComboBox] QComboBox will now reset its root
model index when a new model is set on it.

Task-number: QTBUG-43350
Change-Id: I113d558ce19fcaed31f13abfbedc7a24302e28d7
Reviewed-by: Gabriel de Dietrich <gabriel.dedietrich@theqtcompany.com>
This commit is contained in:
Giuseppe D'Angelo 2014-12-18 16:18:16 +01:00
parent 14583137ae
commit 940530ab67
2 changed files with 27 additions and 0 deletions

View File

@ -1986,6 +1986,8 @@ void QComboBox::setModel(QAbstractItemModel *model)
this, SLOT(_q_emitHighlighted(QModelIndex)), Qt::UniqueConnection);
}
setRootModelIndex(QModelIndex());
bool currentReset = false;
if (count()) {
@ -2024,6 +2026,8 @@ QModelIndex QComboBox::rootModelIndex() const
void QComboBox::setRootModelIndex(const QModelIndex &index)
{
Q_D(QComboBox);
if (d->root == index)
return;
d->root = QPersistentModelIndex(index);
view()->setRootIndex(index);
update();

View File

@ -1577,11 +1577,34 @@ void tst_QComboBox::setModel()
QCOMPARE(box.currentIndex(), 0);
QVERIFY(box.model() != oldModel);
// set a new root index
QModelIndex rootModelIndex;
rootModelIndex = box.model()->index(0, 0);
QVERIFY(rootModelIndex.isValid());
box.setRootModelIndex(rootModelIndex);
QCOMPARE(box.rootModelIndex(), rootModelIndex);
// change the model, ensure that the root index gets reset
oldModel = box.model();
box.setModel(new QStandardItemModel(2, 1, &box));
QCOMPARE(box.currentIndex(), 0);
QVERIFY(box.model() != oldModel);
QVERIFY(box.rootModelIndex() != rootModelIndex);
QVERIFY(box.rootModelIndex() == QModelIndex());
// check that setting the very same model doesn't move the current item
box.setCurrentIndex(1);
QCOMPARE(box.currentIndex(), 1);
box.setModel(box.model());
QCOMPARE(box.currentIndex(), 1);
// check that setting the very same model doesn't move the root index
rootModelIndex = box.model()->index(0, 0);
QVERIFY(rootModelIndex.isValid());
box.setRootModelIndex(rootModelIndex);
QCOMPARE(box.rootModelIndex(), rootModelIndex);
box.setModel(box.model());
QCOMPARE(box.rootModelIndex(), rootModelIndex);
}
void tst_QComboBox::setCustomModelAndView()