From 0f9062ec71021c256dba7ee8498f036d7aac0821 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sat, 26 Oct 2024 11:00:14 +0200 Subject: [PATCH] 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.9 6.8 6.5 6.2 Fixes: QTBUG-130275 Change-Id: Id0c245e185acc36e5d07cea1d22619bb0e9eee07 Reviewed-by: Richard Moe Gustavsen --- src/widgets/kernel/qboxlayout.cpp | 11 +++++++---- .../auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp | 10 ++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/widgets/kernel/qboxlayout.cpp b/src/widgets/kernel/qboxlayout.cpp index 501883e85a9..00860f14ebc 100644 --- a/src/widgets/kernel/qboxlayout.cpp +++ b/src/widgets/kernel/qboxlayout.cpp @@ -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() diff --git a/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp b/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp index a9122d634e3..91902b5fee0 100644 --- a/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp +++ b/tests/auto/widgets/kernel/qboxlayout/tst_qboxlayout.cpp @@ -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"