使用智能指针重写代码时,QDockWidget不会显示

时间:2017-04-22 12:11:29

标签: qt smart-pointers

我希望屏幕上显示QDockWidget,因此我使用了此代码:

QDockWidget *dock = new QDockWidget("Title-1", this) //'this' is the main window
dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
this->addDockWidget(Qt::LeftDockWidgetArea, dock);

它按预期工作:屏幕上出现QDockWidget

但是当我尝试重写实现智能指针的代码时,它不会显示在屏幕上。这是代码(我已经包含<memory>):

std::unique_ptr<QDockWidget> dock(new QDockWidget("Project", this));
dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);

addDockWidget(Qt::LeftDockWidgetArea, dock.get());

有人可以解释为什么它不起作用吗?

1 个答案:

答案 0 :(得分:0)

Qt使用Object Trees & Ownership的概念,特别是对于GUI类(QWidget的衍生物)。如果您将父QWidget传递给constructor of a QWidget,则会在父母破坏时自动销毁该子项。因此,这些类不需要任何智能指针类型。

使用智能指针可能会过早地破坏QDockWidget(即当唯一指针超出范围时,例如在局部变量的函数返回时),因此该项将从父{{1}中删除}}