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;
LoudQVBoxLayout* mainlayout = new LoudQVBoxLayout;
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?
source
share