What is parent for in Qt?

Mas Bagol picture Mas Bagol · May 20, 2015 · Viewed 14.2k times · Source

Almost every QtWidgets class can have parent. And usually it's optional to set parent at object initialization. For example,If I create a class that inherits QWidget class, I will do the following on the constructor:

Widget::Widget(QWidget* parent): QWidget(parent) {
    hbox = new QHBoxLayout(this);
    yes_button = new QPushButton("&Yes");
    no_button = new QPushButton("&No", this);
    cancel_button = new QPushButton("&Cancel", hbox);
}

I can set or not set parent. I can set cancel_button to be a child of hbox. I can too set cancel_button to be a child of yes_button, but I think it's a bad thing to do.

What's the point of this? And, is it really necessary to set parent for every QWidget based class that I create?

Answer

Vitor picture Vitor · May 20, 2015

Besides helping with draw order in GUI objects, it also helps with memory management, so that when you destroy a QObject, all of it's children are destroyed too. See http://doc.qt.io/qt-4.8/objecttrees.html for more details. When something changes in the parent (e.g. when it is resized), it can notify its children to update themselves too.

To answer your question, you're not required to set the parent for everything (that's why it's an optional parameter, after all), but most of the time it's better to set it correctly.