0

I know this has been asked several times in different posts, however I am still not convinced that my implementation is the best solution.

I have a QVBoxLayout in which I add a QHBoxLayout which hold widgets. The QVBoxLayout by default is empty.

I delete all layouts widgets using this code, however the widgets can fire signals. Is this save? Also I would rather want to change it to a recursive function as shown in https://stackoverflow.com/questions/4272196/qt-remove-all-widgets-from-layout/7077340#=

QLayoutItem *child;
while ((child = ui->verticalLayoutAmplitude->takeAt(0)) != 0)  {
    QLayoutItem * subchild;
    while ((subchild = child->layout()->takeAt(0)) != 0)  {
        delete subchild->widget();
        delete subchild;
    }
    delete child->widget();
    delete child;
}

What I do not understand is why it is so complicated.

Also the creation of the widgets could be different The parent layout can not be used in the creation of the widgets. Thus only the MainWindow as a parent class was inserted. I wonder what else should be inserted as a parent class?

for (int i = 0; i < parameterList.size(); ++i) {

    QString valueName = parameterList.at(i);
    double value = parameter(valueName);

    QHBoxLayout * hLayout = new QHBoxLayout(this);
    QDoubleSpinBox * spinbox = new QDoubleSpinBox();
    QLabel * label = new QLabel();
    label->setText(valueName);
    spinbox->setValue(value);

    hLayout->addWidget(label, 1);
    hLayout->addWidget(spinbox, 3);
    ui->verticalLayoutAmplitude->addLayout(hLayout);
}
Community
  • 1
  • 1
Matthias Pospiech
  • 3,130
  • 18
  • 55
  • 76
  • You should not delete `QObject` instances directly that are owned by other `QObject`'s, it is potentially unsafe. Use `deleteLater()` instead. – RobbieE Aug 13 '16 at 07:34
  • Ok. The other question is wheter the new widgets should have a parent and which? – Matthias Pospiech Aug 13 '16 at 20:27
  • Unsure why that way to remove the widget from layout from some post in stackoverflow is better than documented http://doc.qt.io/qt-5/qlayout.html#removeWidget? Especially with all those delete ptr; which you can still do but first pLayout->removeWidget(pWidget); pWidget->setParent(nullptr); delete pWidget; and btw with own void QLayout::removeItem you don't need to go through nested ones. You also don't really need to rush to delete all the objects as long as they still belong to layout as parent-child QObject. – Alexander V Aug 14 '16 at 00:19
  • `removeWidget` is not usefull for layouts. I have it organised as VLayout->HLayout->Widgets. Second: I do not know the pointers. I would need to store them in a separate list. This would not be cleaner than what I do know. – Matthias Pospiech Aug 14 '16 at 18:24
  • Note: `QHBoxLayout(this)` is not allowed, it would set the layout of MainWindow. Thus all Layouts and Widgets have no parent and must have no parent as far as I understand. – Matthias Pospiech Aug 14 '16 at 18:25

0 Answers0