PDA

View Full Version : Ownership in a QWidget



tuli
22nd March 2015, 15:20
A quick question:

QWidget::setLayout takes ownership of the layout and QLayout::addWidget takes ownership of the passed widgets. How does it know when to delete an object and when not? Or: why does this work:




class test : public QWidget
{
public:
test()
{
QHBoxLayout* l = new QHBoxLayout();
l->addWidget(&bar);
setLayout(l);
}
QScrollBar bar;
};


Why doesn't a double free occur, once when the layout discards the scrollbar and once when the test dtor?

wysota
22nd March 2015, 16:41
The destructor of test is executed before the destructor of QWidget so bar gets deleted (and removed from the layout) before QWidget destructor has a chance to delete the layout.

tuli
22nd March 2015, 17:32
Ah I understand now. Thank you. Is this a common pattern or is it better to allocate one at runtime with "new QScrollBar()" ?

Radek
22nd March 2015, 19:09
Well, it "works": On destroying test you get orphaned QHBoxLayout with an invalid item bar (now deleted). The QHBoxLayout needs to specify a parent


QHBoxLayout *l = new QHBoxLayout(this);

or l needs to be a data item of test and test needs a dtor which will delete l. Naturally, specifying the parent is a way simpler and cleaner.

wysota
22nd March 2015, 20:13
Well, it "works": On destroying test you get orphaned QHBoxLayout with an invalid item bar (now deleted). The QHBoxLayout needs to specify a parent


QHBoxLayout *l = new QHBoxLayout(this);

or l needs to be a data item of test and test needs a dtor which will delete l.

setLayout() does an implicit setParent() of the layout to the widget so the layout will be destroyed when the widget it manages is destroyed.

anda_skoa
23rd March 2015, 08:57
Ah I understand now. Thank you. Is this a common pattern or is it better to allocate one at runtime with "new QScrollBar()" ?

Child widgets are usually allocated on the heap.
Keeps the headers clean from includes that are internals to the parent widget.

Cheers,
_