mercredi 27 mai 2015

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

I am trying to pass a QWidget pointer argument (plot2) to Qt's addWidget(QWidget * T,...) function that takes a pointer to a QWidget as its first argument. If I pass the raw pointer plot2, I get the two side-by-side panels as expected.

raw pointer version

    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);

However, if I use std::unique_ptr version of plot2 and pass the pointer via std::unique_ptr(plot2) as shown in the following snippet, the panel associated with plot2 goes missing without the compiler making any complaints.

smart pointer version

    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

I have tried using a std::shared_ptr but the result remains the same.

What works of course is if I release() the std::unique_ptr associated with plot2 as follows, but then to my understanding I lose the use of the smart pointer version of plot2 henceforth.

using 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);

Can you figure out how to get this working?

Aucun commentaire:

Enregistrer un commentaire