Skip to content

Commit

Permalink
Do not remove non-widget items when removeWidget() called with nullptr
Browse files Browse the repository at this point in the history
child->widget() returns null if the layout item is not a widget.
Thus, calling removeWidget(nullptr) will remove all non-widget items
such as layouts or strechers.

Change-Id: I772c1158d0f7e8e2850b6e571b0405a2896f09b8
Pick-to: 6.0 6.1 5.15
Reviewed-by: Tor Arne Vestbø <[email protected]>
Reviewed-by: David Faure <[email protected]>
  • Loading branch information
Piotr Srebrny committed May 11, 2021
1 parent 1e85dfa commit 867c0b8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/widgets/kernel/qlayout.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1355,6 +1355,11 @@ QRect QLayout::alignmentRect(const QRect &r) const
*/
void QLayout::removeWidget(QWidget *widget)
{
if (Q_UNLIKELY(!widget)) {
qWarning("QLayout::removeWidget: Cannot remove a null widget.");
return;
}

int i = 0;
QLayoutItem *child;
while ((child = itemAt(i))) {
Expand Down
24 changes: 24 additions & 0 deletions tests/auto/widgets/kernel/qlayout/tst_qlayout.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ private slots:
void controlTypes2();
void adjustSizeShouldMakeSureLayoutIsActivated();
void testRetainSizeWhenHidden();
void removeWidget();
};

tst_QLayout::tst_QLayout()
Expand Down Expand Up @@ -398,5 +399,28 @@ void tst_QLayout::testRetainSizeWhenHidden()
QCOMPARE(widget.sizeHint().height(), normalHeight);
}

void tst_QLayout::removeWidget()
{
QHBoxLayout layout;
QCOMPARE(layout.count(), 0);
QWidget w;
layout.addWidget(&w);
QCOMPARE(layout.count(), 1);
layout.removeWidget(&w);
QCOMPARE(layout.count(), 0);

QPointer<QLayout> childLayout(new QHBoxLayout);
layout.addLayout(childLayout);
QCOMPARE(layout.count(), 1);

layout.removeWidget(nullptr);
QCOMPARE(layout.count(), 1);

layout.removeItem(childLayout);
QCOMPARE(layout.count(), 0);

QVERIFY(!childLayout.isNull());
}

QTEST_MAIN(tst_QLayout)
#include "tst_qlayout.moc"

0 comments on commit 867c0b8

Please sign in to comment.