What does the constructor "MyWindow::MyWindow(QWidget* parent) : QMainWindow(parent)" mean?



  • Hi,

    I have a sample question.

    In the constructor function, what does the (QWidget* parent) : QMainWindow(parent)" component mean?

    Or can anybody tell me where I can find the explanation to this?

    Thanks a lot.


  • Moderators

    MyWindow is a subclass of QMainWindow.

    That line is the start of your MyWindow constructor. It calls QMainWindow constructor.

    See http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules



  • Hi, Thank you. Now I know that it calls the QMainWindow's constructor. But could tell me the meantings of two "parent" parameters in this line? I was confused by those parameters. Sorry for these simple questions. But I am at the beginning of learning this. I've tried to find it out in many ways. But I failed. Thanks again for your time.

    Regards

    [quote author="JKSH" date="1410999197"]MyWindow is a subclass of QMainWindow.

    That line is the start of your MyWindow constructor. It calls QMainWindow constructor.

    See http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules[/quote]



  • Hi about those "parent" params. they are used when you want a windows hierarchy, say you have a main window and you want to construct smaller windows (QWidgets) inside it; when you create the small window you pass along the main window as the "parent" argument to the constructor.
    Then they are connected, so that the small window follows the big one around when you drag it or resize etc.

    If you look at your mainwindow.h file you'll see that the "parent" argument is a default argument that can be 0, and in 99.99% of Qt programs that's what happening, i.e. you main.cpp constructs a Mainwindow w that's the top window, because no parent is specified.
    So this code your question is about, to pass along a parent QWidget, is almost never used :-)


  • Moderators

    Hi,

    To expand on hskoglund's answer, the parent parameter lets you set parent-child relationships. A less-common way to do this is to call the QWidget::setParent() function.

    The '0' mentioned by hskoglund refers to a NULL pointer. If you pass in a NULL pointer, the widget will have no parent.

    A child widget's memory is managed by its parent -- when a parent is destroyed, its children are automatically destroyed too.

    See the article, "Object Trees and Ownership":http://qt-project.org/doc/qt-5/objecttrees.html for more details.

    P.S. Please don't feel sorry for asking! We're glad to help :)



  • Thanks to you two.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.