2

I have a QDialog subclass that contains a spacer as its only immediate child; all of the window’s UI elements are contained in the spacer. The user cannot change the window size directly, but UI elements will be shown or hidden as the user interacts with the window. I’d like the dialog to resize each time this happens so that the spacer (and the dialog itself) always takes up the minimum possible amount of space. How can I configure my dialog and my spacer to get the desired behavior?

(This question dealt with something similar, although in that case the user was able to resize the window. It was also not clear to me what the OP actually ended up doing in that case.)

Community
  • 1
  • 1
bdesham
  • 15,430
  • 13
  • 79
  • 123

2 Answers2

4

You can resize the window to minimumSizeHint() after the number of widgets is changed :

resize(minimumSizeHint());

This will shrink the window to minimum size. But you should consider that the minimum size is not computed until some events are processed in the event loop. So after some widgets are hidden and some other are shown, just process the event loop for some iterations and then resize to minimum.

It's like :

for(int i=0;i<10;i++)
   qApp->processEvents();

resize(minimumSizeHint());

A better solution is to single shot a QTimer which calls a slot in which you resize the window to minimum. This way when you resize the window, the minimum size hint is computed correctly.

Nejat
  • 31,784
  • 12
  • 106
  • 138
  • The `QTimer` solution seems more robust, as it's unclear how many times `processEvents` needs to be called (possibly it's platform-dependent). Also see this Qt Forum thread: [Resize top level window to fit contents](https://forum.qt.io/post/80850). – ekhumoro Jun 26 '20 at 12:50
1

void QWidget::adjustSize()

Adjusts the size of the widget to fit its contents.

Community
  • 1
  • 1
iMath
  • 2,326
  • 2
  • 43
  • 75