Clarification on deleting layouts and widgets within them
Solved
General and Desktop
-
Hello Qt Universe,
I would like some clarification and some help on something I'm working on. Let's say that I have the following:
note: this wasn't copied from my code so please forgive syntax errorsQPushButton *btn1, *btn2, *btn3, *btn4, *delBtn; QHBoxLayout *hbox1, *hbox2; QVBoxLayout *vbox1; btn1 = new QPushButton(Tr("1"); btn2 = new QPushButton(Tr("2"); btn3 = new QPushButton(Tr("3"); btn4 = new QPushButton(Tr("4"); delBtn = new QPushButton(Tr("del"); connect(delBtn, &QPushButton::clicked, this, &MyClass::delBtnClicked); hbox1 = new QHBoxLayout; hbox1->addWidget(btn1); hbox1->addWidget(btn2); hbox2 = new QHBoxLayout; hbox2->addWidget(btn3); hbox2->addWidget(btn4); vbox1 = new QVBoxLayout; vbox1->addLayout(hbox1); vbox1->addLayout(hbox2); setLayout(vbox1); void MyClass::delBtnClicked() { //remove and delete entire vbox1 layout }
I've seen the following:
QLayoutItem *child; while ((child = layout->takeAt(0)) != 0) { ... delete child; }
Would each hbox be "child" and "layout" would be vbox? And if I delete "child" will that then delete the QPushButton widgets within hbox1 and hbox2?
Thanks!
-
Hi,
Most likely yes.
-
Well I got my example to work by using the following:
while(!vbox1->isEmpty()) { QLayout *hb = vbox1->takeAt(0)->layout(); while(!hb->isEmpty()) { QWidget *w = hb->takeAt(0)->widget(); delete w; } delete hb; } delete vbox1;
This removes the widgets and the layout they're on, as well as deletes them from memory. Thanks!
-
No, it doesn't. The QLayoutItem is not the parent of the widget, it is not a QObject. That's not its job.