Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does owner of QBoxLayout become the owner of all layout widgets?

Tags:

c++

qt

I was looking at the example here, and was wondering if there is no memory leaks. I have red the article talking about the subjet mem leak on delete. However while QWidgets do retain ownership of the of the widget added to the, the layout do not.

It seems from the QT code that the parent with the layout, gets the ownership of all the widgets for this layout. However i could not seen any reference of this in docs.

Window::Window()
{
 editor = new QTextEdit();
 QPushButton *sendButton = new QPushButton(tr("&Send message"));

 connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage()));

 QHBoxLayout *buttonLayout = new QHBoxLayout();
 buttonLayout->addStretch();
 buttonLayout->addWidget(sendButton);
 buttonLayout->addStretch();

 QVBoxLayout *layout = new QVBoxLayout(this);
 layout->addWidget(editor);
 layout->addLayout(buttonLayout);

 setWindowTitle(tr("Custom Type Sending"));
}
like image 306
Anton Avatar asked Apr 17 '12 17:04

Anton


2 Answers

From Layout Management:

Tips for Using Layouts

When you use a layout, you do not need to pass a parent when constructing the child widgets. The layout will automatically reparent the widgets (using QWidget::setParent()) so that they are children of the widget on which the layout is installed.

Note: Widgets in a layout are children of the widget on which the layout is installed, not of the layout itself. Widgets can only have other widgets as parent, not layouts.

You can nest layouts using addLayout() on a layout; the inner layout then becomes a child of the layout it is inserted into.

like image 128
Diego Schulz Avatar answered Oct 15 '22 05:10

Diego Schulz


No, QLayouts do not take ownership of managed QWidgets.

Here is the implementation of addWidget():

void QLayout::addWidget(QWidget *w)
{
    addChildWidget(w);
    addItem(QLayoutPrivate::createWidgetItem(this, w));
}

Explanation:

  1. addChildWidget() simply ensures that the managed widget w is removed from other layouts.

  2. createWidgetItem(this, w) allocates a new QWidgetItem. This QWidgetItem stores a pointer to w, but do not take ownership of w.

  3. addItem() adds the item to the layout, and takes ownership of the QWidgetItem (not of the QWidget observed by the QWidgetItem). This means that the QWidgetItem will de destroyed when the QLayout is destroyed. However, the QWidget w will still not be destroyed.

The QWidget will be destroyed when its parent QWidget is destroyed. Such parent is assigned automatically by the QLayout when parent->setLayout(layout) is called.

like image 4
Boris Dalstein Avatar answered Oct 15 '22 04:10

Boris Dalstein