我想替换QDockWidget *的小部件(QWidget *),但调用setWidget(),则删除以前的小部件。如何防止这种删除?

QDockWidget* dw = new QDockWidget;
QWidget* tw1 = new TestWidget;
QWidget* tw2 = new TestWidget;
dw->setWidget(tw1);
dw->setWidget(tw2); // tw1 deleted here
delete dw;
// I want to use tw1 here, but it died


TestWidget只是检查删除时刻的测试:

class TestWidget : public QWidget {
public:
    TestWidget(QWidget* parent = nullptr)
        : QWidget(parent)
    {
        cout << "TestWidget() " << this << endl;
    }
    ~TestWidget() override {
        cout << "~TestWidget() " << this << endl;
    }
};

最佳答案

QDockWidget* dw = new QDockWidget;
QWidget* tw1 = new TestWidget;
QWidget* tw2 = new TestWidget;
dw->setWidget(tw1);
dw->setWidget(tw2);
tw1->setParent(0);
delete dw; // dw and tw2 deleted here, but not tw1

07-28 06:40