Search code examples
c++qtlayoutparent

Getting Parent Layout in Qt


Is there any way to retrieve the parent layout of a widget in Qt?

QObject::parent() won't work, for logical reasons.

I'm positive the widget has a parent layout, because I added it to a layout earlier in the code. Now, I have many other layouts in the window and while it is possible for me to keep track of them, I just want to know if there is an easy and clean way to get the parent layout by using the Qt API.

I'm adding the widget to the layout like this:

QHBoxLayout* layout = new QHBoxLayout;
layout->addWidget(button);

Solution

  • After some exploration, I found a "partial" solution to the problem.

    If you are creating the layout and managing a widget with it, it is possible to retrieve this layout later in the code by using Qt's dynamic properties. Now, to use QWidget::setProperty(), the object you are going to store needs to be a registered meta type. A pointer to QHBoxLayout is not a registered meta type, but there are two workarounds. The simplest workaround is to register the object by adding this anywhere in your code:

    Q_DECLARE_METATYPE(QHBoxLayout*)
    

    The second workaround is to wrap the object:

    struct Layout {
        QHBoxLayout* layout;
    };
    Q_DECLARE_METATYPE(Layout)
    

    Once the object is a registered meta type, you can save it this way:

    QHBoxLayout* layout = new QHBoxLayout;
    QWidget* widget = new QWidget;
    widget->setProperty("managingLayout", QVariant::fromValue(layout));
    layout->addWidget(widget);
    

    Or this way if you used the second workaround:

    QHBoxLayout* layout = new QHBoxLayout;
    QWidget* widget = new QWidget;
    Layout l;
    l.layout = layout;
    widget->setProperty("managingLayout", QVariant::fromValue(l));
    layout->addWidget(widget);
    

    Later when you need to retrieve the layout, you can retrieve it this way:

    QHBoxLayout* layout = widget->property("managingLayout").value<QHBoxLayout*>();
    

    Or like this:

    Layout l = widget->property("managingLayout").value<Layout>();
    QHBoxLayout* layout = l.layout;
    

    This approach is applicable only when you created the layout. If you did not create the layout and set it, then there is not a simple way of retrieving it later. Also you will have to keep track of the layout and update the managingLayout property when necessary.