我对在 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 方法有点不同。
QObject
类constructor接受一个指向父 QObject
的指针。当父 QObject
被破坏时,其子代也将被破坏。这是整个 Qt 类中非常普遍的模式,您会注意到很多构造函数都接受 *parent
参数。
如果你看一些 Qt example programs您会发现它们实际上在堆上构造了大多数 Qt 对象,并利用此对象树来处理破坏。我个人发现这个策略也很有用,因为 GUI 对象可以有特殊的生命周期。
如果您不使用QObject
或 QObject
的子类(例如 QWidget
),Qt 不提供超出标准 C++ 的额外保证。
在您的特定示例中,不能保证任何内容都会被删除。
Des
需要这样的东西(假设 Des
是 QWidget
的子类):
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/