简体   繁体   中英

Qt Widget not showing when using std::unique_ptr

I am trying to dynamically insert a new QLabel onto my main window. It works fine if I don't use std::unique_ptr and I can see the QLabel being drawn at my window. Why can't I use std::unique_ptr or 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)
  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 . This is wrong, because both parties assume they are sole owners, and in consequence your Qlabel may be freed twice.

Your second example is perfectly valid. It works, and no resources are leaked - your QLabel will be deallocated by its parent 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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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