You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There is nothing particularly wrong with it, but there is more Qt-ish way of writing it.
In Qt, QObject and everything that derives from it (QWidget, QLabel, even your own class, etc), can take ownership of other QObjects through so called parent-child relationship, which is usually specified in the constructor or as a call to QObject::setParent.
For example, that's how you could reduce the code above if you would use this parent-child relation:
Note that we removed the destructor.
Here layout is told to be a child of MyWidget by passing this as parent argument to to QVBoxLayout's constructor QVBoxLayout::QVBoxLayout(QWidget * parent ). This means that when MyWidget is destroyed, it will also delete layout. The same is true for label.
Also, if you don't access layout and label variables from anywhere outside the constructor, you don't even have to make them class members.
Moreover, you don't need to call setLayout(layout), because by passing this to QVBoxLayout's constructor you already are specifying that layout is the layout of MyWidget.
From documentation for void QWidget::setLayout ( QLayout * layout ):
An alternative to calling this function is to pass this widget to the layout's constructor.
I see you write code like this:
There is nothing particularly wrong with it, but there is more Qt-ish way of writing it.
In Qt, QObject and everything that derives from it (QWidget, QLabel, even your own class, etc), can take ownership of other QObjects through so called parent-child relationship, which is usually specified in the constructor or as a call to
QObject::setParent
.For example, that's how you could reduce the code above if you would use this parent-child relation:
Note that we removed the destructor.
Here
layout
is told to be a child ofMyWidget
by passingthis
asparent
argument to to QVBoxLayout's constructorQVBoxLayout::QVBoxLayout(QWidget * parent )
. This means that whenMyWidget
is destroyed, it will also deletelayout
. The same is true forlabel
.Also, if you don't access
layout
andlabel
variables from anywhere outside the constructor, you don't even have to make them class members.Moreover, you don't need to call
setLayout(layout)
, because by passingthis
to QVBoxLayout's constructor you already are specifying thatlayout
is the layout of MyWidget.From documentation for
void QWidget::setLayout ( QLayout * layout )
:Here is a doc explaining parent-child relationship a bit more.
The text was updated successfully, but these errors were encountered: