Why Parent class in constructor?
-
wrote on 22 Jun 2020, 05:57 last edited by VRonin
I was strolling through the Qt examples and saw this:
class MainWidget : public QWidget { Q_OBJECT public: explicit MainWidget(QWidget *parent = 0); .... }
I was curious to know why do we need to pass a parent object to the constructor? Is this only to maintain a parent-child relationship or does it serve some another purpose as well?
And what does this statement do? : MainWidget::MainWidget(QWidget *parent) : **QWidget(parent)** { }
We initialize a QWidget object with the parent here but what does it actually do?
Thanks -
I was strolling through the Qt examples and saw this:
class MainWidget : public QWidget { Q_OBJECT public: explicit MainWidget(QWidget *parent = 0); .... }
I was curious to know why do we need to pass a parent object to the constructor? Is this only to maintain a parent-child relationship or does it serve some another purpose as well?
And what does this statement do? : MainWidget::MainWidget(QWidget *parent) : **QWidget(parent)** { }
We initialize a QWidget object with the parent here but what does it actually do?
Thanks@pk23081996 said in Why Parent class in constructor?:
Is this only to maintain a parent-child relationship
Yes, parent/child.
What parent means for QWidget based classes (in addition to parent/child based memory management) can be found here: https://doc.qt.io/qt-5/qwidget.html#QWidget -
I was strolling through the Qt examples and saw this:
class MainWidget : public QWidget { Q_OBJECT public: explicit MainWidget(QWidget *parent = 0); .... }
I was curious to know why do we need to pass a parent object to the constructor? Is this only to maintain a parent-child relationship or does it serve some another purpose as well?
And what does this statement do? : MainWidget::MainWidget(QWidget *parent) : **QWidget(parent)** { }
We initialize a QWidget object with the parent here but what does it actually do?
Thankswrote on 22 Jun 2020, 13:52 last edited by@pk23081996 said in Why Parent class in constructor?:
We initialize a QWidget object with the parent here but what does it actually do?
Look at the documentation about object trees & ownership. One main benefit is:
When you create a QObject with another object as parent, it's added to the parent's children() list, and is deleted when the parent is
1/3