I'm very confused about using destructors in Qt4 and hope, you guys can help me.
When I have a method like this (with "Des" is a class):
void Widget::create() {
Des *test = new Des;
test->show();
}
how can I make sure that this widget is going to be deleted after it was closed?
And in class "Des" i have this:
Des::Des()
{
QPushButton *push = new QPushButton("neu");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(push);
setLayout(layout);
}
where and how do I have to delete *push and *layout? what should be in the destructor Des::~Des() ?
Another option to using
deleteLater()
, or parents, is to use the delete-on-close functionality for widgets. In this case, Qt will delete the widget when it is done being displayed.I like to use it with the object tree that Qt keeps, so that I set delete-on-close for the window, and all widgets in the window have a proper parent specified, so they all get deleted as well.
In most cases you should create widgets on the stack:
This way, they get deleted when they become out of scope. If you really want to create them on the heap, then it's your responsibility to call delete on them when they are not needed anymore.
Qt uses what they call object trees and it's a bit different from the typical RAII approach.
The
QObject
class constructor takes a pointer to a parentQObject
. When that parentQObject
is destructed, its children will be destroyed as well. This is a pretty prevalent pattern throughout Qt's classes and you'll notice a lot of constructors accept a*parent
parameter.If you look at some of the Qt example programs you'll find that they actually construct most Qt objects on the heap and take advantage of this object tree to handle destruction. I personally found this strategy useful as well, as GUI objects can have peculiar lifetimes.
Qt provides no additional guarantees beyond standard C++ if you're not using
QObject
or a subclass ofQObject
(such asQWidget
).In your particular example there's no guarantee that anything gets deleted.
You'll want something like this for
Des
(assumingDes
is a subclass ofQWidget
):And you'd use class
Des
like so:This tutorial suggests you don't need to explicitly delete widgets that have been added to parent widgets. It also says it doesn't hurt to do delete them either.
(I've not tested this, but I guess as long as you explicitly delete them before the parent widget is deleted, this should be OK.)
Richardwb's answer is a good one - but the other approach is to use the deleteLater slot, like so:
Obviously the closed() signal can be replaced with whatever signal you want.