tom
tom

Reputation: 1344

Parent-Child relation in Qt

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);
}
  1. signalMapper

    As it is constructed with parameter this, when the parent object ButtonWidget is deleted, it is also deleted.

    Is this correct?

  2. gridLayout

    Why does the gridLayout not require to be created by new QGridLayout(this)?

  3. 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

Answers (1)

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

  1. Yes. When a parent is specified for a 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);
  2. The reason is that 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);
  3. Same as 2, after 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

Related Questions