我从 Qt 文档中知道 QLayout
对象拥有其小部件的所有权。但就 QLayout
对象而言,在堆栈上创建它然后使用 setLayout
函数将其传递给小部件是否安全?还是必须在堆上创建?
#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();
}
两种选择// 在栈上和//在堆上在退出时产生相同的结果:
~LoudQVBoxLayout()
~LoudPushButton()
~LoudPushButton()
但是我能确定这不是未定义的行为吗? window
是否在其布局上调用了 delete
?
编辑:
鉴于Cat Plus Plus的回答我猜想:
LoudPushButton button;
mainlayout->addWidget(&button);
mainlayout->addWidget(new LoudPushButton);
即使 button
和 *mainlayout
保证同时被删除,也会产生未定义的行为。这是真的吗?
最佳答案
每个 QObject
都会删除它的子对象。只有没有父对象的对象才能有自动存储。 QWidget::setLayout
重新设置布局的父级。所以,不,你不能用 QLayout
做到这一点。
关于c++ - 在堆栈上创建 QLayout 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10399304/