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

QDockWidget doesn't show when code get rewritten with 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());

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

Qt 使用了Object Trees & Ownership, especially for GUI classes (derivatives of QWidget). If you pass a parent QWidget to the constructor of a QWidget 的概念,child 会在parent 销毁时自动销毁。因此,这些 类.

不需要任何智能指针类型

使用智能指针可能会过早破坏您的 QDockWidget(即当唯一指针超出范围时,例如在局部变量的函数 return 上),因此该项目将被删除来自 parent QWidget.