c++ QObject's Child Management

#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QWidget>
int main (int argc, char* argv[]) {
QApplication app (argc, argv);
QWidget window;
QLabel* label = new QLabel("Please enter some text");
QTextEdit* textEdit = new QTextEdit;
QVBoxLayout* layout = new QVBoxLayout;
layout->addwidget(label);
layout->addwidget(textEdit);
window.setLayout(layout);
window.show;
return app.exec();
}

Questions:

1.Qt provides a child management facility through the QObject class. Where is the QObject in the program above? Explain

2.The QObject class provides the function setParent(QObject *parent) to specify a Qbject to be its parent. Why is this function not use in this program?

3.The program uses both heap and stack objects. Explain how the parnt-child facility works when the:

a.parent is a heap obhect and the child objects are stack objects
b.parent is a stack obhect and the child objects are heap objects
This is not the right place to ask about Qt. I think you wanna go try www.qt-project.org's forum. However,

1. For the child management, you have to pass the pointer/reference of your QObject to the child, for example:

1
2
3
4
QWidget window;
QLabel* label = new QLabel("Please enter some text",&window);
QTextEdit* textEdit = new QTextEdit(&window);
QVBoxLayout* layout = new QVBoxLayout(&window);


with this you have them registered in window object, and whenever window is deleted, those object will be deleted as well.

2. You can use this parent-child thing in two ways, either like I described it above, or:

1
2
3
QWidget window;
QLabel* label = new QLabel("Please enter some text",&window);
label->setParent(&window);


3. In your example, the parent is allocated on the stack, since it doesn't use the word "new". The childs, however, are allocated on the heap, and that's why it's safe to have some parent for them to handle their clean-up and have them deleted automatically.

a. parent on the heap, just have your QWidget as a pointer:

1
2
3
4
5
6
7
8
9
QWidget *window = new QWidget;
QLabel* label = new QLabel("Please enter some text",window); //notice, & is not used since it's a pointer


...

//when you're done with window, you have to delete it, and all childs will be deleted automatically
delete window;
return app.exec();


and I think that childs on the stack won't need a parent, and it's even wrong to do that, because the parent will try to delete them and you'd get a segmentation fault. Note that stack objects are deleted automatically when they're out of scope (out of the {} brackets).
Last edited on
Topic archived. No new replies allowed.