将std::unique_ptr.get()作为参数传递给addWidget()

passing std::unique_ptr.get() as a parameter to addWidget()

本文关键字:addWidget 参数传递 get std unique ptr      更新时间:2023-10-16

我正试图将一个QWidget指针参数(plot2(传递给QtaddWidget(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);

但是,如果我使用plot2std::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。