Important: Please read the Qt Code of Conduct -

Error messages in the log when assigning QGroupBox a layout

  • I have a Designer form class in which I need to generate some UI parts programmatically. Specifically, I have a QGroupBox in the UI file and I need to generate its content. I start by supplying it a QHBoxLayout via groupBox->setLayout(). That immediately results in the following debug output in the log:

    QWidget::setLayout: Attempting to set QLayout "" on QGroupBox "_pauseScalingGroupbox", which already has a layout
    QLayout: Cannot add layout QHBoxLayout/ to itself

    And indeed, I checked the groupBox->layout() before all that and it's not null. But I have no layout for that widget in the UI file. I've double-checked in the ui_.h file.
    How can I replace the default layout with mine gracefully?

    Note that everything works, my layout actually functions. It's just the debug messages that bug me. I don't like UB.

  • Lifetime Qt Champion

    See the documentation :
    "If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout."

  • @jsulm
    Ah! I've tried setLayout(nullptr) but that was also forbidden. Totally didn't think about deleting it.

    Tried that. The first message disappeared, the second one remained (Cannot add layout QHBoxLayout/ to itself), and I'm getting access violation as soon as I place the first widget into the layout. Odd.

    Here's the specific code: QGridLayout in a QHBoxLayout, widgets in the QGridLayout.

  • In your code try to remove the parent from pauseControlLayout i.e

    QGridLayout * pauseControlLayout = new QGridLayout(ui->_pauseScalingGroupbox); // remove parent
    pauseControlLayout->setColumnStretch(2, 2);
    QHBoxLayout * pauseControlGroupLayout = new QHBoxLayout();
    ui->_pauseScalingGroupbox->setLayout(pauseControlGroupLayout); // which layout you want to set ? QHBoxLayout or QGridLayout ?
    pauseControlGroupLayout->addLayout(pauseControlGroupLayout); // pauseControlGroupLayout is adding to itself ??

  • @Sam
    Wow, that was indeed that typo that caused all the trouble. All because of terrible naming of the two layout objects. Thanks!

Log in to reply