[SOLVED] QObject::setParent() vs passing this as parent
-
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
-
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.
-
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.