views:

150

answers:

3

If I want to create my own class MyWidget which inherits from QWidget

Tutorial tells me to write constructor like this...

MyWidget::MyWidget(QWidget *parent)
: QWidget(parent){....}

I'm wondering what is the role of : QWidget(parent)

Does it mean explicit call for QWidget's constructor?

A: 

Hi.

From "yours" Qt tutorial: Because this class inherits from QWidget, the new class is a widget and may be a top-level window or a child widget (like the QPushButton in the previous chapter).

Good luck!

mosg
+3  A: 

Yes. In C++, if you must explicitly call the base class's constructor in your constructor's initialization list if you want it to run. In this case, QWidget(parent) would be run before running the code in your constructor. By the way, this is not just a Qt thing, but is common in C++ inheritance.

Jason
+2  A: 

In addition to the previous answer:

1 Like it was mentioned if parent not null you widget will be rendered just inside parent widget.

2 If parent widget is deleted you all his child widgets will be also deleted by delete operator.

Correct implementation of default widget constructor should be the following:

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

MyWidget::MyWidget(QWidget *parent = 0): QWidget(parent) {
    // Your own initialization code
}

Try to avoid specifing nonzero parent for stack widget. You'd better always create nested widget in the way:

QWidget *parentWidget;
MyWidget myWidget = new MyWidget(parentWidget);

You can read more here: http://doc.trolltech.com/4.6/objecttrees.html

VestniK