QBoxLayout: don't crash on passing invalid index

Passing an invalid index gives an assertion in debug mode and crashes in
release mode due to an out-of-bounds access. Fix it by appending the
given widget (same as passing a negative index which is documented).

Pick-to: 6.8 6.5 6.2
Fixes: QTBUG-130275
Change-Id: Id0c245e185acc36e5d07cea1d22619bb0e9eee07
Reviewed-by: Richard Moe Gustavsen <richard.gustavsen@qt.io>
(cherry picked from commit 0f9062ec71021c256dba7ee8498f036d7aac0821)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Christian Ehrlicher 2024-10-26 11:00:14 +02:00 committed by Qt Cherry-pick Bot
parent 72f48d0840
commit 3c0f08ab70
2 changed files with 17 additions and 4 deletions

View File

@ -413,8 +413,9 @@ int QBoxLayoutPrivate::validateIndex(int index) const
if (index < 0)
return list.size(); // append
Q_ASSERT_X(index >= 0 && index <= list.size(), "QBoxLayout::insert", "index out of range");
return index;
if (index > list.size())
qWarning("QBoxLayout::insert: index %d out of range (max: %d)", index, int(list.size()));
return index <= list.size() ? index : list.size();
}
/*!
@ -811,8 +812,10 @@ void QBoxLayout::addItem(QLayoutItem *item)
}
/*!
Inserts \a item into this box layout at position \a index. If \a
index is negative, the item is added at the end.
Inserts \a item into this box layout at position \a index.
Index must be either negative or within the range 0 to count(),
inclusive. If \a index is negative or count(), the item is
added at the end.
\sa addItem(), insertWidget(), insertLayout(), insertStretch(),
insertSpacing()

View File

@ -42,6 +42,7 @@ private slots:
void taskQTBUG_40609_addingLayoutToItself();
void replaceWidget();
void indexOf();
void invalidIndex();
};
class CustomLayoutStyle : public QProxyStyle
@ -584,5 +585,14 @@ void tst_QBoxLayout::indexOf()
QCOMPARE(inner->indexOf(inner->itemAt(0)), 0);
}
void tst_QBoxLayout::invalidIndex()
{
QLabel lbl("aaa");
QVBoxLayout layout;
layout.insertWidget(1, &lbl); // should not crash
QVERIFY(layout.itemAt(0));
QCOMPARE(layout.itemAt(0)->widget(), &lbl);
}
QTEST_MAIN(tst_QBoxLayout)
#include "tst_qboxlayout.moc"