tags:

views:

97

answers:

2

Hi

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 can 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.

+2  A: 

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.

Caleb Huitt - cjhuitt
I decided to write a method which is automatically called when the orientation changes, that(after removing) adds the widgets again into the layout.
ExplodingRat
+1  A: 

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
Roku