Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Unsolved Why Parent class in constructor?

    General and Desktop
    3
    3
    304
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • P
      pk23081996 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

      jsulm Pablo J. Rogina 2 Replies Last reply Reply Quote 0
      • jsulm
        jsulm Lifetime Qt Champion @pk23081996 last edited by

        @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

        https://forum.qt.io/topic/113070/qt-code-of-conduct

        1 Reply Last reply Reply Quote 2
        • Pablo J. Rogina
          Pablo J. Rogina @pk23081996 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

          Upvote the answer(s) that helped you solve the issue
          Use "Topic Tools" button to mark your post as Solved
          Add screenshots via postimage.org
          Don't ask support requests via chat/PM. Please use the forum so others can benefit from the solution in the future

          1 Reply Last reply Reply Quote 1
          • First post
            Last post