Demod
Demod

Reputation: 53

C++, Qt : deallocation of "non attribute" objects created in constructor

In the following example of a Qt class, many objects are created in the constructor and in functions called by the constructor, but are not pointed at by attribute pointers and, from what I understood, cannot be deleted in the destructor (there is at not point in any of the files the keyword delete).

http://qt-project.org/doc/qt-4.8/widgets-groupbox.html

in window.h

class Window : public QWidget
{
    Q_OBJECT

public:
     Window(QWidget *parent = 0);

private:
     QGroupBox *createFirstExclusiveGroup();
     QGroupBox *createSecondExclusiveGroup();
     QGroupBox *createNonExclusiveGroup();
     QGroupBox *createPushButtonGroup();
};

in window.cpp

Window::Window(QWidget *parent)
     : QWidget(parent)
 {
     QGridLayout *grid = new QGridLayout;
     grid->addWidget(createFirstExclusiveGroup(), 0, 0);
     grid->addWidget(createSecondExclusiveGroup(), 1, 0);
     grid->addWidget(createNonExclusiveGroup(), 0, 1);
     grid->addWidget(createPushButtonGroup(), 1, 1);
     setLayout(grid);

     setWindowTitle(tr("Group Boxes"));
     resize(480, 320);
 }

 QGroupBox *Window::createFirstExclusiveGroup()
 {
     QGroupBox *groupBox = new QGroupBox(tr("Exclusive Radio Buttons"));

     QRadioButton *radio1 = new QRadioButton(tr("&Radio button 1"));
     QRadioButton *radio2 = new QRadioButton(tr("R&adio button 2"));
     QRadioButton *radio3 = new QRadioButton(tr("Ra&dio button 3"));

     radio1->setChecked(true);

     QVBoxLayout *vbox = new QVBoxLayout;
     vbox->addWidget(radio1);
     vbox->addWidget(radio2);
     vbox->addWidget(radio3);
     vbox->addStretch(1);
     groupBox->setLayout(vbox);

     return groupBox;
 }

Am I missing something or is it a "bad" example of implementation ? Would a correct implementation be to put the pointers as attribute of class Window and destroy what they point at in ~Window() ? Thank you.

Upvotes: 0

Views: 101

Answers (1)

Flovdis
Flovdis

Reputation: 3095

Because all objects are added to the object tree, they are deleted automatically.

E.g. all widgets are added to the layout, and the layout itself is set in the window. This creates a tree of objects.

You can use the method QObject::dumpObjectTree() to get a visual representation of the current tree of objects.

See also Object Trees & Ownership in the Qt documentation for details.

Upvotes: 2

Related Questions