The difference between Qwidget object and pointer
-
-
[quote author="jandin" date="1294109520"]Thanks for your response. If I just follow the Qt doc "Getting Started Programming with Qt",I think I would get mad. :-)[/quote]
Unfortunately the sample code in the Getting Started Guide is wrong and causes the application to crash. See the thread "Getting started example is buggy":http://developer.qt.nokia.com/forums/viewthread/2253/, it has a working version of the sample.
-
[quote author="Gerolf" date="1294128379"]Hi,
it goes a but farer. You should give the textedit a parent, as the text edit is not automatically reparented. So it should look like this:[/quote]
Actually not; putting it into the layout will automatically reparent it.
-
[quote author="Volker" date="1294147102"][quote author="Gerolf" date="1294128379"]it goes a but farer. You should give the textedit a parent, as the text edit is not automatically reparented.[/quote]
It actually is reparented. That's why the sample program of the getting started guide crashes.[/quote]
But it's only reparented, if the layout already is set to a widget, so creating the layout, adding widgets and the setting the layout to it's parent does not work.
-
[quote author="Gerolf" date="1294155697"]
But it's only reparented, if the layout already is set to a widget, so creating the layout, adding widgets and the setting the layout to it's parent does not work.[/quote]Yes it does. And does the right thing.
@
#include <QtGui>int main(int argc, char **argv)
{
QApplication app(argc, argv);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(new QTextEdit);
QWidget w;
w.setLayout(layout);
w.show();
return app.exec();
}
@ -
[quote author="peppe" date="1294156553"]Yes it does. And does the right thing.[/quote]
Correct. It is a two step process:
- layout takes ownership of the text edit on addWidget()
- widget w takes ownership of the layout on setLayout() and thus on all of the layout's widgets
-
[quote]layout takes ownership of the text edit on addWidget()[/quote]
No :-)
A QLayout cannot own a text edit. Remember: widgets can have only another widget as parent. Not arbitrary QObjects.
What happens is that the QLayout simply "remembers" about the text edit; the reparenting happens when setLayout() is called. After that, the hierarchy will be something like
- QWidget
** QLayout
** QTextEdit
(notice that the layout and the text edit are siblings and both children of the QWidget).
- QWidget
-
Peppe, your right. I mixed up things from what I looked up in the sources some times ago. The layout only keeps book of the widgets it manages, but does not take ownership.
But what's really important for the users: After the UI is set up, all parent-child relationships are correct. I really do like Qt :-)