开发者

Qt: Same Widget Inside Two Different Layouts

开发者 https://www.devze.com 2023-01-16 19:37 出处:网络
What I\'m trying to achieve is that a widget could exist in two different layouts, in this case in QHBoxLayout and in QVBoxLayout. I\'m implementing a system which dynamically switches between the two

What I'm trying to achieve is that a widget could exist in two different layouts, in this case in QHBoxLayout and in QVBoxLayout. I'm implementing a system which dynamically switches between the two layouts when a device's screen orientation changes.

Currently I'm creating, let's say a complex composite widget called MyWidget and adding it into a two different layouts:

MyWidget *wgt = new QWidget();
QVBoxLayout vlayout;
QHBoxLayout hlayout;

vlayout->addWidget(wgt);
hlayout->addWidget(wgt);

Now imagine that both layouts are hosted within a 'root' layout, and that this root layout ca开发者_JAVA百科n resize into a more wide than tall 'landscape' mode, and into a more tall than wide 'portrait' mode.

The MyWidget shows correctly in only the first layout it is added into, and when the layouts are switched, it shows all wrong or not at all.

I don't know if I'm making any sense here, but this is my problem. Maybe when the switch event is called all child widgets and layouts should be resized, so it would always look right. Only problem is that I don't know how.


This isn't a general solution for changing layouts, but an easy solution in your case: Just change the boxlayout's direction.

hlayout->setDirection(QBoxLayout::TopToBottom);
// now your hboxlayout works as vertical layout

hlayout->setDirection(QBoxLayout::LeftToRight);
// and now it is horizontal again


This isn't particularly easy to do, but is possible.

First of all, I'd recommend that you actually create two different widgets, one for the vertical and one for the horizontal, and manage things that way. If the source data is properly separated from the UI class, you should be able to do so without too much trouble, but by incurring some memory overhead.

One way to do as you desire would be to completely remove the widgets from one layout and add them to the other when you need to change the arrangement on the screen, and change the layout that is added to the widget. This should cause the same widgets to be drawn in a different way.

A different, more intricate way of handling this (although potentially more efficient) would be to write your own layout and have it handle rearranging widgets based on the orientation change.

0

精彩评论

暂无评论...
验证码 换一张
取 消