Reputation: 1344
I would like to clear the concept of how children are deleted when they are created by new
.
This code example is from http://doc.qt.io/qt-4.8/qsignalmapper.html
ButtonWidget::ButtonWidget(QStringList texts, QWidget *parent)
: QWidget(parent)
{
signalMapper = new QSignalMapper(this);
QGridLayout *gridLayout = new QGridLayout;
for (int i = 0; i < texts.size(); ++i) {
QPushButton *button = new QPushButton(texts[i]);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(button, texts[i]);
gridLayout->addWidget(button, i / 3, i % 3);
}
connect(signalMapper, SIGNAL(mapped(const QString &)),
this, SIGNAL(clicked(const QString &)));
setLayout(gridLayout);
}
signalMapper
As it is constructed with parameter this
, when the parent object ButtonWidget
is deleted, it is also deleted.
Is this correct?
gridLayout
Why does the gridLayout
not require to be created by new QGridLayout(this)
?
button
It is created in a for loop which mean it will be out of scope after each loop. Under normal situation, there should be memory leak if it is not deleted within the loop. So, does it make memory leak in this program?
Upvotes: 3
Views: 3433
Reputation: 29966
QObject
, it takes ownership of that object. When a parent object is deleted, it will delete all it's child objects (all objects that it owns);setLayout
sets a layout for a widget and gives the ownership of this layout to the widget. So after setLayout
is called, the grid layout is owned by the ButtonWidget
and it will delete it when needed (i.e. when ButtonWidget
itself will be deleted);gridLayout->addWidget(button, i / 3, i % 3);
is called, the ownership of button
will change. Technically, addWidget
calls addItem
, so a QWidgetItem
is created. The layout takes ownership of that item, and the parent widget takes ownership of the widget. Anyway, the button will be destroyed on the destruction ot it's parent widget.Upvotes: 6