c++ - Qt4 中的析构函数

标签 c++ qt qt4 destructor

我对在 Qt4 中使用析构函数感到非常困惑,希望你们能帮助我。
当我有这样的方法时(“Des”是一个类):

void Widget::create() {
    Des *test = new Des;
    test->show();
}

如何确保该小部件在关闭后会被删除?

在“Des”课上我有这个:

Des::Des()
{
    QPushButton *push = new QPushButton("neu");
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(push);
    setLayout(layout);
}

我必须在哪里以及如何删除 *push 和 *layout?析构函数 Des::~Des() 应该是什么?

最佳答案

Qt 使用他们所说的 object trees它与典型的 RAII 方法有点不同。

QObjectconstructor接受一个指向父 QObject 的指针。当父 QObject 被破坏时,其子代也将被破坏。这是整个 Qt 类中非常普遍的模式,您会注意到很多构造函数都接受 *parent 参数。

如果你看一些 Qt example programs您会发现它们实际上在堆上构造了大多数 Qt 对象,并利用此对象树来处理破坏。我个人发现这个策略也很有用,因为 GUI 对象可以有特殊的生命周期。

如果您不使用 QObjectQObject 的子类(例如 QWidget),

Qt 不提供超出标准 C++ 的额外保证。


在您的特定示例中,不能保证任何内容都会被删除。

Des 需要这样的东西(假设 DesQWidget 的子类):

class Des : public QWidget
{
    Q_OBJECT

public:
    Des(QWidget* parent)
    : QWidget(parent)
    {
        QPushButton* push = new QPushButton("neu");
        QHBoxLayout* layout = new QHBoxLayout(this);
        layout->addWidget(push); // this re-parents push so layout 
                                 // is the parent of push
        setLayout(layout);
    }

    ~Des()
    {
        // empty, since when Des is destroyed, all its children (in Qt terms)
        // will be destroyed as well
    }
}

你会像这样使用 Des 类:

int someFunction()
{
    // on the heap
    Des* test = new Des(parent); // where parent is a QWidget*
    test->show();
    ...
    // test will be destroyed when its parent is destroyed

    // or on the stack
    Des foo(0);
    foo.show();
    ...
    // foo will fall out of scope and get deleted
}

关于c++ - Qt4 中的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1436904/

相关文章:

c++ - 从专用模板方法调用非专用模板方法

c++ - C++ 运算符优先级表中的后增量与赋值

c++ - C++ 中的字符串生产者/消费者:std::deque<char> 还是 std::stringstream?

c++ - 调用接收派生类列表的方法不会在 C++ 中编译

qt - 在Windows上以管理员身份运行Qt应用程序

c++ - Qt ActiveX 动态调用返回值始终为空

qt - Qt 为什么不使用异常处理?

qt - 添加一个节点到 QDomNodeList

c++ - Qt4 QTableWidget 使 Column resize to contents, interactive and aligned to table border

qt - 在 Ubuntu 18.04.1 LTS 中安装 Qt 4.8.7