8

Let's consider we have a QWidget and a QLayout named general_layout that contains other widgets and layouts. general_layout is set as the QWidget layout like this:

setLayout(general_layout)

Now I should to change the content of QWidget. How can I do that? I have tried to delete and create a new layout for the QWidget and that new layout set as a layout of the QWidget, but could not complete my intentions successfully.

This is my code:

delete general_layout;
general_layout = new QHBoxLayout;
general_layout->addLayout(some_layout);
myQWidget->setLayout(general_layout);
msrd0
  • 7,816
  • 9
  • 47
  • 82
Narek
  • 38,779
  • 79
  • 233
  • 389
  • Could you be more specific about your problem? What you are doing seems to be correct (ie delete old layout before setting a new one). – mtvec Jun 07 '10 at 14:38
  • Sure! I do the following: delete general_layout; general_layout = new QHBoxLayout; general_layout->addLayout(some_layout); myQWidget->setLayout(general_layout); – Narek Jun 07 '10 at 14:57

1 Answers1

15

The problem is that the widgets of a layout are not destroyed when deleting a layout. This results in all child widgets of myQWidget still being present, be it without a layout.

The solution is simple: add a

qDeleteAll(myQWidget->children());

after

delete general_layout;
mtvec
  • 17,846
  • 5
  • 52
  • 83
  • Seems that was the problem. Thanks a lot!!! Just one more question too. I want to have a dialog that changes its structure (in the aspect of this question). So I do that with creating layout, deleting and creating a new one. Is that a good approach? – Narek Jun 07 '10 at 15:32
  • 4
    Could be if you don't need the first structure anymore. If you do, using QStackedLayout (http://doc.trolltech.com/latest/qstackedlayout.html) is much easier. If you're trying to implement something like a wizard, take a look at QWizard (http://doc.trolltech.com/latest/qwizard.html). – mtvec Jun 07 '10 at 15:37
  • qDeleteAll(myQWidget->children()); function deletes all childs, but what about child of the childs. I mean within the child elements of myQWidget there are no layouts which are child layout of general_layout. When I call a method of a child layout of general_layout, my application blows up (so I guest that pointer is destroyed), but when I check if it equals to 0 (m_childLayout_of_General_Layout == 0), then if statement is ignored. What's the matter? Is it deleted or no? – Narek Jun 07 '10 at 18:08
  • 1
    Yes, all children (direct or indirect) are deleted (take a look at http://doc.qt.nokia.com/latest/qobject.html#dtor.QObject). In C++, calling delete on a pointer does not set this pointer to 0. That's why your if-statement does not work. As I said before, if you still need the old widgets, using a QStackedLayout might be the way to go. – mtvec Jun 08 '10 at 09:10
  • Perhaps you should be making the child widgets children of the layout they are in, as opposed to their logical grandparent? – Troyseph Mar 31 '15 at 14:48