I am following Qt Tutorials and got a simple question
If I want to create my own class MyWidget which inherits from QWidget
The tutorial wrote me a constructor like this ...
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent){....}
I am wondering what the role is: QWidget (parent)
Does this mean an explicit call to the QWidget constructor?
a source to share
Yes. In C ++, if you have to explicitly call the base class constructor in your constructor the initialization list if you want to run it. In this case, it QWidget(parent)
will run before the code runs in your constructor. By the way, this is not just a Qt thing, but also common in C ++ inheritance.
In addition to the previous answer:
1 As mentioned, if the parent is not null, the widget will only be displayed inside the parent widget.
2 If the parent widget is deleted, all of its child widgets will also be deleted by the delete operator.
The correct implementation of the default widget constructor should be as follows:
class MyWidget: public QWidget {
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
}
MyWidget::MyWidget(QWidget *parent = 0): QWidget(parent) {
// Your own initialization code
}
Try not to specify a non-null parent for the stack widget. It's better to always create nested widgets:
QWidget *parentWidget;
MyWidget myWidget = new MyWidget(parentWidget);
You can read more here: http://doc.trolltech.com/4.6/objecttrees.html
a source to share
This is called an initialization list in C ++, and yes, it is an explicit call to the QWidget constructor. By default, C ++ calls the no-argument version of base class constructors if there is no explicit call in the initialization list. It is generally considered a good construct that the initialization of class members is handled by this class constructor - Qt follows this convention. So, here you are passing a pointer to your base class constructor so that it can store it in one of its member variables.
a source to share