PDA

View Full Version : to free or not to free



masoroso
17th April 2006, 18:44
Hi all,

I am new to this forum and it looks like a great resource for Qt information. I am used to Delphi so it's Qt as well as C++ I'll have to learn :) but it sure looks good what Trolltech did!

Now to the question.

I am not sure on the memory stuff. What is automagically destroyed and what is not?

Here is a piece of code of my test project:



VerticalDialog::VerticalDialog(QWidget *parent)
: QDialog(parent)
{
VerticalItemModel *vertical = new VerticalItemModel;
lytMain = new QGridLayout(this);

lytSurface = new QHBoxLayout();
lytOkCancel = new QHBoxLayout();
lytOpenSave = new QHBoxLayout();

//table
tblVertical = new QTableView();
tblVertical->setAlternatingRowColors(true);
tblVertical->setModel(vertical);
...


Do I need to free the memory myself (for example for the QHBoxLayout classes) or does Qt take care of this? I do not assign a parent to them so there is nobody `to take care of them'??

Thanks in advance,
Rob

jacek
17th April 2006, 18:56
What is automagically destroyed and what is not?
Every QObject which has a parent will be destroyed when its parent is destroyed.


I do not assign a parent to them so there is nobody `to take care of them'??
Well... some object might adopt them. ;)


void QLayout::addItem ( QLayoutItem * item ) [pure virtual]
Implemented in subclasses to add an item. How it is added is specific to each subclass.
The ownership of item is transferred to the layout, and it's the layout's responsibility to delete it.


When you use a layout, you don't need to pass a parent when constructing the child widgets. The layout will automatically reparent the widgets (using QWidget::setParent()) so that they are children of the widget on which the layout is installed.
Important: Widgets in a layout are children of the widget on which the layout is installed, not of the layout itself. Widgets can only have other widgets as parent, not layouts.
You can nest layouts using addLayout() on a layout; the inner layout then becomes a child of the layout it is inserted into. The Basic Layouts example uses this feature to create a complex dialog.