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"