Search code examples
qtuser-interfaceqt4show-hide

Qt: making a layout's children invisible/visible


I have a QHBoxLayout and I want to make its children invisible and then visible later. I've tried all kinds of combinations of QWidget::findChildren(), QObject::children() and QLayout::widget(), but none of these work. The first 2 return empty lists and the 2nd returns a NULL.


Solution

  • The widgets aren't children of a layout: a QWidget can be only a child of a QWidget, and QLayout is not a widget. You must recursively enumerate the layout's elements instead. Recall that QLayout is-a QLayoutItem:

    void setLayoutVisible(QLayoutItem *item, bool visible) {
      if (auto widget = item->widget())
        return widget->setVisible(visible);
      if (auto layout = item->layout())
        for (int i = 0; i < layout->count(); ++i)
          setLayoutVisible(layout->itemAt(i), visible);
    };