Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
Donald Duck Avatar asked Nov 27 '16 15:11

Donald Duck


2 Answers

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.

like image 90
skypjack Avatar answered Sep 18 '22 02:09

skypjack


You cannot have the same object in multiple places. There is only once instance of it and it lives in only one single location. You can only have multiple references. Granted, a layout doesn't take a widget instance, but a reference (pointer) to it, but Qt's design is such that adding a widget to a layout will transfer ownership to the layout's underlying widget. And it makes sense, the two layouts may call for a different widget geometry, and how does a single widget have two geometries in the same time? Even if possible theoretically, it is not possible without abstracting the geometry away from the widget, and in Qt's case the geometry is part of the widget, so it is not possible. And that's just one of the many aspects which make such reuse/sharing challenging and not really viable.

Depending on what you want to achieve you could:

  • reuse GUI elements - in that case roll out YourOwnWidget : public QWidget, then you can instantiate in as many times as you want

  • share the same data across multiple GUI elements, in addition to the previous step, what you really want to do is put the data in a separate, non-visible object, then you can create and bind as many types and instances of GUI elements to it as you want.

like image 30
dtech Avatar answered Sep 20 '22 02:09

dtech