在 Qt 的两个不同布局中使用相同的小部件
我想在 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);
小部件在 layout2
中应有的样子,但在 layout1
中不可见.
The widget is as it should in layout2
but is not visible in layout1
.
一种解决方法是创建两个不同的 myWidget
小部件,但我想知道是否有更好的方法.
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?
推荐答案
addWidget
将所有权从 layout1
转移到 layout2
.
对象树是 Qt 用来组织对象的方式.例如,具有父项的项目显示在其父项的坐标系中,并被其父项的边界以图形方式裁剪.
您可以尝试解决该限制,但这不是您应该如何使用 Qt,我不会建议它.
如果您需要两个小部件,请创建两个小部件.这就是 Qt 的设计方式和使用方式.
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.
请参阅此处了解有关 Qt 对象模型的更多详细信息.
See here for further details about the Qt's objects model.
相关文章