Donald Duck Donald Duck - 12 days ago 7
C++ Question

Use the same widget in two different layouts in Qt

I would like to use the same widget in two different layouts in Qt. Here is my code:

QWidget *myWidget = new QWidget;

QFormLayout *layout1 = new QFormLayout;
layout1->addWidget(myWidget);

QFormLayout *layout2 = new QFormLayout;
layout2->addWidget(myWidget);


The widget is as it should in
layout2
but is not visible in
layout1
.

A workaround would be to create two different
myWidget
widgets, but I would like to know if there is a better way of doing.

Why does this happen and what is the correct way of doing this?

Answer

addWidget transfers the ownership from layout1 to layout2.
Object trees are the way Qt uses to organize objects. As an example, an item that has a parent is displayed in its parent's coordinate system and is graphically clipped by its parent's boundaries.
You can try to work around the limitation, but it is not how you should use Qt and I won't suggest it.
If you need two widgets, create two widgets. That's how Qt is designed and how it should be used.

See here for further details about the Qt's objects model.