SASM icon indicating copy to clipboard operation
SASM copied to clipboard

Use Qt's parent-child relationship

Open nurupo opened this issue 11 years ago • 1 comments

I see you write code like this:

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    MyWidget(QWidget *parent = 0) : QWidget(parent)
    {
        layout = new QVBoxLayout;
        label = new QLabel("Hello");
        layout->addWidget(label);
        setLayout(layout);
    }

    ~MyWidget()
    {
        delete layout;
        delete label;
    }

private:
    QVBoxLayout *layout;
    QLabel *label;
};

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:

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    MyWidget(QWidget *parent = 0) : QWidget(parent)
    {
        QVBoxLayout *layout = new QVBoxLayout(this);
        QLabel *label = new QLabel("Hello", this);
        layout->addWidget(label);
    }
};

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.

Here is a doc explaining parent-child relationship a bit more.

nurupo avatar Jul 19 '14 09:07 nurupo

Thank you! I'll refactor code according this in the future commits.

Dman95 avatar Jul 20 '14 15:07 Dman95