c++ - 使用 std::unique_ptr 时 Qt Widget 不显示

标签 c++ qt c++11

我正在尝试将新的 QLabel 动态插入到我的主窗口中。如果我不使用 std::unique_ptr 它工作正常并且我可以看到在我的窗口中绘制的 QLabel。为什么我不能使用 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();
}

最佳答案

您的代码有两个问题:

std::unique_ptr<QLabel> shrd_QLabel = make_unique<QLabel>();  // 1
shrd_QLabel->setParent(this);                                 // 2
  1. 您创建了一个在作用域结束时释放的智能指针(当 MainWindow 的构造函数返回时)
  2. 您分配 ownership您的 QLabelMainWindow,所以您的 QLabel 现在有两个所有者 - 一个是 unique_ptr,第二个是父级主窗口。这是错误的,因为双方都假定他们是唯一所有者,因此您的 Qlabel 可能会被释放两次。

你的第二个例子是完全有效的。它有效,并且没有资源泄漏 - 您的 QLabel 将由其父级 MainWindow 释放。请注意,不是:

QLabel * lpQLabel = new QLabel();
lpQLabel->setParent(this);

你可以这样做:

QLabel * lpQLabel = new QLabel(this); // lpQLabel is owned by `this`

关于c++ - 使用 std::unique_ptr 时 Qt Widget 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32815435/

相关文章:

python - 使用 QPainter 更改线条的位置

c++ - 有没有办法在 QtCreator 中将 QWidget 添加到 QMenu

c++ - 如何使 std::regex 在字符串中的特定位置开始匹配?

c++ - 在 Intellisense 中评估枚举中的字符串常量

c++ - QObject::connect 的函数包装器

c++ - 如何将数组存储在 Sqlite3 的一列中?

c++ - 防止 C++03 代码在 C++11 中表现不佳的好方法?

arrays - 为什么禁止内置 "braced-init-list"中的 "operator[]"?

c++ - Thread Sanitizer 是否可用?

c++ - 如何在 C++ 中制作正方形