QLayout::setSizeConstraint(QLayout::SetFixedSize)
solves this problem well when you prefer keeping your widget's size fixed at all times — that is, if you'd like it to always be fixed to its "packed" size (which may still vary as the child widgets change size).
That is what the "fixed" means there: "fixed" to the correct size, even as the latter varies. (In Qt terms, what I'm calling the "packed" size is simply the widget's sizeHint
.)
But a constraint may be too strong a solution in some instances. In particular, if you apply it to a top-level window, then the user will not be free to resize the window.
If you don't like that, you can instead perform the "set size to sizeHint
" operation instantaneously each time it's needed, rather than imposing it as an unrelenting constraint. The way to do that is to call QWidget::adjustSize()
.
Note that if the container whose children are changing size is not the top-level window, then adjustSize()
may have to be called recursively on the container and its parents. (In my case, I had to do that, anyway. I also tried the size-constraint scheme, and found that applying the constraint at only the topmost level was successful in compacting all levels. I haven't enough knowledge of Qt to comment usefully on these observations, so I merely share them.)