Is it possible to create a QLayout on the stack?

I know that in the Qt documentation, an object QLayoutassumes ownership of its widgets. But as for the object QLayout, is it possible to create it on the stack and then pass it to the widget using a function setLayout? Or should it be created on a heap?

#include <iostream>

#include <QtGui/QApplication>
#include <QPushButton>
#include <QVBoxLayout>

class LoudPushButton : public QPushButton
{
public:
    virtual ~LoudPushButton(){std::cout << "~LoudPushButton()" << std::endl;}
};

class LoudQVBoxLayout : public QVBoxLayout
{
public:
    virtual ~LoudQVBoxLayout(){std::cout << "~LoudQVBoxLayout()" << std::endl;}
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QWidget window;

    // On the heap
    LoudQVBoxLayout* mainlayout = new LoudQVBoxLayout;
    mainlayout->addWidget(new LoudPushButton);
    mainlayout->addWidget(new LoudPushButton);
    window.setLayout(mainlayout);
  /*
    // On the stack
    LoudQVBoxLayout mainlayout;
    mainlayout.addWidget(new LoudPushButton);   
    mainlayout.addWidget(new LoudPushButton);
    window.setLayout(&mainlayout);
  */
    window.show(); 

    return a.exec();
}

Both alternatives // On the stack and // On the heap produce the same output:

~LoudQVBoxLayout()
~LoudPushButton()
~LoudPushButton()

But can I be sure that this is not undefined behavior? Does the windowcall deleteon its layout?

EDIT:

In response to Cat Plus Plus's answer, I assume that:

LoudPushButton button;
mainlayout->addWidget(&button);
mainlayout->addWidget(new LoudPushButton);

It produces undefined behavior, even if button, and *mainlayoutare guaranteed to be removed at the same time. It's true?

+3
source share
2 answers

Qt , QWidgets . , . undefined.

Qt , :

int main()
{
    QWidget window;
    QPushButton quit("Quit", &window);
    ...
}

: quit , ++ (ISO/IEC 14882: 2003) , . child, quit, , , , .

, . QWidget::setLayout :

, QWidget . ( layout()), setLayout() .

Qt QLayout, QWidgets, , . QLayout , QWidget, .

+1

QObject . . QWidget::setLayout . , , QLayout.

+4

All Articles