[英]Qt Widget not showing when using std::unique_ptr
I am trying to dynamically insert a new QLabel onto my main window.我正在尝试在我的主窗口中动态插入一个新的 QLabel。 It works fine if I don't use std::unique_ptr and I can see the QLabel being drawn at my window.
如果我不使用 std::unique_ptr 并且我可以看到在我的窗口中绘制的 QLabel ,它就可以正常工作。 Why can't I use std::unique_ptr or std::shared_ptr?
为什么我不能使用 std::unique_ptr 或 std::shared_ptr?
MainWindow::MainWindow(QWidget *parent):QMainWindow(parent)
{
setWindowFlags(Qt::FramelessWindowHint);
ui.setupUi(this);
std::unique_ptr<QLabel> shrd_QLabel = make_unique<QLabel>();
shrd_QLabel->setParent(this);
shrd_QLabel->setText("test");
shrd_QLabel->setGeometry(70, 70, 70, 70);
shrd_QLabel->show();
//The above doesnt work, however, below example works perfectly
QLabel * lpQLabel = new QLabel();
lpQLabel->setParent(this);
lpQLabel->setText("TEST #2");
lpQLabel->setGeometry(70, 170, 70, 70);
lpQLabel->show();
}
Your code has two problems:您的代码有两个问题:
std::unique_ptr<QLabel> shrd_QLabel = make_unique<QLabel>(); // 1
shrd_QLabel->setParent(this); // 2
MainWindow
returns)MainWindow
构造函数返回时)QLabel
to MainWindow
, so your QLabel
has now two owners - one is unique_ptr
, and the second is parent MainWindow
.QLabel
所有权分配给MainWindow
,因此您的QLabel
现在有两个所有者 - 一个是unique_ptr
,第二个是父MainWindow
。 This is wrong, because both parties assume they are sole owners, and in consequence your Qlabel
may be freed twice.Qlabel
可能会被释放两次。 Your second example is perfectly valid.你的第二个例子是完全有效的。 It works, and no resources are leaked - your
QLabel
will be deallocated by its parent MainWindow
.它可以工作,并且没有资源泄漏 - 您的
QLabel
将被其父级MainWindow
解除分配。 Note, that instead of:请注意,而不是:
QLabel * lpQLabel = new QLabel();
lpQLabel->setParent(this);
you could do:你可以这样做:
QLabel * lpQLabel = new QLabel(this); // lpQLabel is owned by `this`
When you use std::unique_ptr
, the object is deleted at the end of the scope, so it's like you did this:当您使用
std::unique_ptr
,对象在作用域的末尾被删除,所以就像您这样做:
QLabel *shrd_QLabel = new QLabel;
shrd_QLabel->setParent(this);
shrd_QLabel->setText("test");
shrd_QLabel->setGeometry(70, 70, 70, 70);
shrd_QLabel->show();
delete shrd_QLabel;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.