将std::unique_ptr.get()作为参数传递给addWidget()
passing std::unique_ptr.get() as a parameter to addWidget()
我正试图将一个QWidget
指针参数(plot2
(传递给Qt
的addWidget(QWidget * T,...)
函数,该函数将指向QWidget的指针作为其第一个参数。如果我传递原始指针plot2
,我会得到预期的两个并排面板。
原始指针版本
plot1 = new QWidget;
plot2 = new QWidget;
gridLayout = new QGridLayout(gridLayoutWidget);
...
gridLayout->addWidget(plot1, 1, 1, 1, 1);
gridLayout->addWidget(plot2.get(), 1, 2, 1, 1);
但是,如果我使用plot2
的std::unique_ptr
版本,并通过std::unique_ptr(plot2(传递指针,如以下代码段所示,则与plot2
相关的面板将丢失,编译器不会提出任何抱怨。
智能指针版本
plot1 = new QWidget;
auto plot2 = std::unique_ptr<QWidget>(new QWidget);
gridLayout = new QGridLayout(gridLayoutWidget);
...
gridLayout->addWidget(plot1, 1, 1, 1, 1);
gridLayout->addWidget(plot2.get(), 1, 2, 1, 1); // this panel goes missing
我尝试过使用std::shared_ptr
,但结果保持不变。
当然,如果我按如下方式release()
与plot2
相关联的std::unique_ptr
,那么会起作用,但据我所知,此后我将不再使用plot2
的智能指针版本。
使用std::unique_ptr.release((
plot1 = new QWidget;
auto plot2 = std::unique_ptr<QWidget>(new QWidget);
gridLayout = new QGridLayout(gridLayoutWidget);
...
gridLayout->addWidget(plot1, 1, 1, 1, 1);
gridLayout->addWidget(plot2.release(), 1, 2, 1, 1);
你能想出如何让它发挥作用吗?
来自文档(强调矿(:
在位置"行"、"列"、"跨行"answers"跨列"处添加项"跨行和跨列",并根据对齐方式对其进行对齐。如果rowSpan和/或columnSpan为-1,则项目将分别延伸到下边缘和/或右边缘布局取得项目的所有权。
当您添加该小部件时,您将不再拥有它,因此存储在std::unique_ptr
中然后调用release
是完全合理的。这实际上比原始指针版本更可取,因为如果在将某个东西添加到布局之前抛出异常,内存将自动回收。
auto plot2 = std::unique_ptr<QWidget>(new QWidget);
plot2超出范围后,您的QWidget*对象将被删除。因为unique_ptr析构函数类似于
~unique_ptr() {delete ptr;}
当QObject被删除时,Qt会删除与之相关的所有gui。
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数