Reputation: 6260
In Qt, how can I have a widget which automatically sizes itself according to the size of it's children?
For example, if I have a QGroupBox
which contains a QHBoxLayout
which contains some QPushButton
s, I would like the QGroupBox
to automatically calculate it's size so that it is no bigger and no smaller than necessary to fit all of the QPushButton
s.
Ideally I would like to be able to do this in Qt Designer so that I can create a .ui
file which already knows how to size the QGroupBox
, however I am also opening to deriving from a class inside a .ui
file and doing the resizing manually.
I have tried placing the QGroupBox
inside it's own layout (with and without a spacer) but this just resizes the QGroupBox
to the smallest possible size so that none of the children are visible.
Upvotes: 0
Views: 938
Reputation: 144
You'll probably have the most luck by sub classing QGroupBox and overriding sizeHint or other sizing functions to loop through children and calculate the minimum bounding rectangle. Depending on how dynamic the group box is, managing connections to new widgets might be a small challenge.
Upvotes: 0
Reputation: 98425
There are two things to pay attention to:
Set the size policies appropriately on the children in the groupbox. You literally need to think what the buttons can do - most likely, you do not want the buttons to either grow or shrink, so setting both of their size policies to Fixed
is the right thing to do. You could, possibly, let the buttons expand horizontally, so the horizontal policy of MinimumExpanding
is an option.
Set the size constraint on the layout in the groupbox to act according to your objective:
ui->groupbox->layout()->setConstraint(QLayout::SetMinAndMaxSize);
Of course, the groupbox will be inside of some layout in its parent window, but that doesn't matter.
Upvotes: 1