[SOLVED] QObject::setParent() vs passing this as parent
-
wrote on 17 Aug 2011, 18:36 last edited by
Hello,
I have two similar code snippets.The first one(Qobject::setParent) is working correct and the second one(this keyword) doesn't.
@IamAQDialog::IamAQDialog()
{
QHBoxLayout *hoz = new QHBoxLayout();
hoz->setParent(this);m_loadButton->setDisabled(true); hoz->addWidget(m_loadButton); m_removeMenuButton->setDisabled(true); hoz->addWidget(m_removeMenuButton); QVBoxLayout *lay = new QVBoxLayout(this); lay->addWidget(m_projectList); lay->addLayout(hoz); setLayout(lay);
}@
output: !http://imageshack.us/photo/my-images/827/setparent.png/()!
@IamAQDialog::IamAQDialog()
{
QHBoxLayout *hoz = new QHBoxLayout(this);m_loadButton->setDisabled(true); hoz->addWidget(m_loadButton); m_removeMenuButton->setDisabled(true); hoz->addWidget(m_removeMenuButton); QVBoxLayout *lay = new QVBoxLayout(this); lay->addWidget(m_projectList); lay->addLayout(hoz); setLayout(lay);
}@
output: !http://imageshack.us/photo/my-images/843/thisparent.png/()!
I am trying to parent the hoz widget in order to avoid mem leak.
thanks in advance
-
wrote on 17 Aug 2011, 18:42 last edited by
Just a remark to your code formatting here in the first section:
[quote author="Giorgos Tsiapaliwkas" date="1313606213"]
@IamAQDialog::IamAQDialog()
{
QHBoxLayout *hoz = new QHBoxLayout();
hoz->setParent(this);m_loadButton->setDisabled(true);
@
[/quote]Apparently you should not use the devnet formatting (at least the underlines) in code sections.
-
wrote on 17 Aug 2011, 18:54 last edited by
[quote author="koahnig" date="1313606536"]=
Apparently you should not use the devnet formatting (at least the underlines) in code sections. [/quote]yes,you have right.
thanks -
wrote on 17 Aug 2011, 18:59 last edited by
There is no need to explicitly set a parent for hoz. addLayout() and setLayout() automatically reparents the layout.
EDIT When passing the parent as ctor parameter the parent's setLayout() method is called, whereas when setting the parent using setParent() it isn't. In your second listing the hoz layout isn't added to the lay layout because it is already set as the layout for this (assumption).
Conclusion. Both listings are "wrong" in their way. Just omit the explicit parenting.
-
wrote on 17 Aug 2011, 19:42 last edited by
[quote author="Lukas Geyer" date="1313607566"] Just omit the explicit parenting.[/quote]
The memory deallocation will happen automatically i guess.Correct?
-
wrote on 17 Aug 2011, 20:04 last edited by
For layouts, if they are correctly added, yes.
What also works is just setting the parent for the top layout (never for child layouts, added by addLayout). -
wrote on 17 Aug 2011, 20:20 last edited by
thanks i will mark it as solved
1/7