In Qt, can I embed child widgets in their parent via composition, or do I have to create them with new
?
class MyWindow : public QMainWindow
{
...
private:
QPushButton myButton;
}
MyWindow::MyWindow ()
: mybutton("Do Something", this)
{
...
}
The documentation says that any object derived from QObject
will automatically destroyed when its parent is destroyed; this implies a call to delete
, whcih in the above example would crash.
Do I have to use the following?
QPushButton* myButton;
myButton = new QPushButton("Do Something", this);
EDIT
The answers are quite diverse, and basically boil down to three possibilities:
delete
heap-allocated objects (How does this work?)delete
on the object (But won't a parent-less widget turn into a top-level window?)Which one is correct?
When discussing objects a "parent-child" relationship implies a hierarchy of objects which can be represented as a tree with parents possessing strong references to their children. If you can draw that tree of objects a "parent" would be closer to the root while a "child" would be closer to a leaf node.
QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect().
Qt provides this, by combining the speed of C++ with the flexibility of the Qt Object Model. Qt adds these features to C++: a very powerful mechanism for seamless object communication called signals and slots. queryable and designable object properties. powerful events and event filters.
You can either call Qt. createComponent() to dynamically create a Component object, or use Qt. createQmlObject() to create an object from a string of QML. Creating a component is better if you have an existing component defined in a QML document and you want to dynamically create instances of that component.
The non-static, non-heap member variables are deleted when that particular object's delete sequence starts. Only when all members are deleted, will it go to the destructor of the base class. Hence QPushButton myButton member will be deleted before ~QMainWindow() is called. And from QObject documentation: "If we delete a child object before its parent, Qt will automatically remove that object from the parent's list of children". Hence no crash will occur.
Object trees & ownership answers your question. Basically when the child object is created on the heap it will be deleted by its parent.
On the other hand when the child object is created on the stack the order of destruction is important. The child will be destroyed before its parent and will remove itself from its parent's list so that its destructor is not called twice.
There is also an example in that link that shows problematic order of destruction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With