[英]When are widgets deleted in Qt (QVBoxLayout class)?
I have some simple code to create a new widget using Qt: 我有一些简单的代码可以使用Qt创建新的小部件:
Dock::Dock() : QDockWidget() {
label = new QLabel(QLatin1String("TEST"));
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(label, 0, Qt::AlignTop);
layout->addStretch(-1);
QWidget* multiWidget = new QWidget();
multiWidget->setLayout(layout);
setWidget(multiWidget);
}
Where label
is a private member QLabel* label
. 其中label
是私有成员QLabel* label
。 My question is: am I responsible for deleting label
in Dock
's destructor? 我的问题是:我应该负责删除Dock
的析构函数中的label
吗?
I tried changing the code so that label
is a std::shared_ptr<QLabel>
: 我尝试更改代码,以便label
是std::shared_ptr<QLabel>
:
Dock::Dock() : QDockWidget() {
label = std::make_shared<QLabel>(QLatin1String("TEST"));
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(label.get(), 0, Qt::AlignTop);
layout->addStretch(-1);
QWidget* multiWidget = new QWidget();
multiWidget->setLayout(layout);
setWidget(multiWidget);
}
So that it is deleted automatically when `Dock' is destroyed but I get an error when I close the program. 这样,当“ Dock”被销毁时,它会被自动删除,但是在关闭程序时出现错误。
In order to properly set up the objects tree you need to do the following: 为了正确设置对象树,您需要执行以下操作:
Here is the code that demonstrates the mentioned approach: 这是演示上述方法的代码:
Dock::Dock()
:
QDockWidget()
{
QWidget* multiWidget = new QWidget;
label = new QLabel(QLatin1String("TEST"), multiWidget); // Set parent
QVBoxLayout* layout = new QVBoxLayout(multiWidget); // Sets layout
layout->addWidget(label, 0, Qt::AlignTop);
layout->addStretch(-1);
setWidget(multiWidget);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.