PDA

View Full Version : Creating a square sized widget in a layout



cboles
22nd April 2006, 07:11
I have a QGridLayout something like this:



QGridLayout gLayout;
gLayout->addWidget(new CustomWidget1,0,0,1,1);
gLayout->addWidget(new CustomWidget2,0,1,1,1);


As you can see above, the two widgets are laid side by side in a single grid cell each, e.g. :

CW1 | CW2

CustomWidget1 has a size determined by the data it is displaying, and it determines the overall height of gLayout.

CustomWidget2 is an optional display that can be shown or hidden. Showing it should expand the dialog width, but not change the height. I would like CW2 to have a width that matches it's height (which is in turn determined by CW1 and gLayout), making it a square widget. I can't seem to figure out how to do this cleanly without CW2 knowing what size CW1 is through poorly encapsulated means.

Put another way:

What is the best way to create a widget with a flexible height that always has an actual width that matches its actual height?

wysota
23rd April 2006, 11:36
In your case it should be the best to reimplement resizeEvent and trigger another resize there to make sure the widget is square.

If you wanted to match the height to width of the widget (so the other way round), you could use QWidget::heightForWidth.

cboles
24th April 2006, 18:50
Thanks - it would be nice if there was a widthForHeight() as well for completeness in the QWidget class.

wysota
24th April 2006, 20:22
I'm sure you can subclass QWidget and implement widthForHeight capabilities.

cboles
1st May 2006, 22:50
True, but none of the Qt layout related classes will know about this new method. I thought that the layout classes call heightForWidth() to help calculate the layout? I may be able to find a way to trick these classes into doing what I want, but it seems like that would rely on knowing their implementation, which could change in the future.


I'm sure you can subclass QWidget and implement widthForHeight capabilities.

yuriry
22nd September 2008, 23:38
I also have a need for widthForHeight() method. A container, QScrollArea, uses a custom flow layout that lays out table views in a single row. The container has horizontal scroll bar but no vertical scroll bar. The table views, on the opposite, do not have horizontal scroll bars and only have vertical scroll bars. The problem is when the container's hight gets small enough so that it cuts-off bottom parts of the tables, the tables need to display vertical scroll bars. When this happens, minimalSizeHint() and sizeHint() need to adjust for the vertical scroll bar's width. But in the Qt layout system there seems to be no way to tell a child widget to compute its width based on the vertical space that the parent can provide for the child. Any advice on how to solve this will be greatly appreciated.

Thank you,
Yuri