tags:

views:

65

answers:

3

hello, I have this snippet of the code:

 #include <QApplication>
 #include <QFont>
 #include <QPushButton>
 #include <QWidget>

 class MyWidget : public QWidget
 {
 public:
     MyWidget(QWidget *parent = 0);
 };

 MyWidget::MyWidget(QWidget *parent)
     : QWidget(parent)
 {
     setFixedSize(200, 120);

     QPushButton *quit = new QPushButton(tr("Quit"), this);
     quit->setGeometry(62, 40, 75, 30);
     quit->setFont(QFont("Times", 18, QFont::Bold));

     connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
 }

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     MyWidget widget;
     widget.show();
     return app.exec();
 }

can somebody please explain what exactly is going on in this line

MyWidget(QWidget *parent = 0);

a little bit difficult understand what is this parent, thanks in advance

+8  A: 

That is an argument to the constructor with a default argument (NULL since NULL is defined as 0 as per the c++ standard). Default meaning passing no parameter is the same as passing NULL.

Since Qt's widgets are arranged in a hierarchal system (parent -> child relationships) parent is the widget which is the "owner" or "container" of the current one (NULL means no parent aka a root widget of sorts). For GUI items a widget will often have the widget it is contained in as its parent.

This is advantageous since when a parent is deleted, it will delete any children is has automatically removing the need for much of the memory management that comes with c++.

Evan Teran
This is right on. If you wish to specify the "parent" of the qt widget you're making, you can pass it in as a parameter. The parent can be whatever you want it to be, though the standard way of using it is to set an objects parent to whatever widget it lays inside of. If you have no need to keep track of the parent, though, the parameter is optional and will default to null (read: 0).
Dave McClelland
This is a very basic fundamental part of Qt, and is minimum knowledge for any Qt developer. A great explanation of the subject is here http://doc.trolltech.com/4.6/objecttrees.html
Casey
A: 

Its a 0 pointer (think NULL without the type), or in Qt terms, "no parent".

Yann Ramin
+1  A: 

The parent argument is for giving parents to new widgets. When given, it is useful for Qt to manage the object tree. (To automatically delete child objects.) It also has the concrete visible effect of "attaching" a new widget to another widget (ie, the parent). In your code however, the parent argument is not ever given, causing the widget to appear as a top level window and not to be deleted by Qt automatically. (It would not require deletion by Qt anyway in that code though.)

Xenakios