简体   繁体   English

使用 std::unique_ptr 时 Qt Widget 不显示

[英]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
  1. You create a smart pointer that is freed at the end of scope (when constructor for MainWindow returns)您创建一个在作用域结束时释放的智能指针(当MainWindow构造函数返回时)
  2. You assign ownership of your 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM