[SOLVED] Resize QMainWindow to minimal size after content of layout changes


I’m using a subclass of QMainWindow, in which I declared a central widget. This widget contains, among other things, a QGridLayout, which holds a set of buttons. The amount of buttons can grow or shrink, depending on the user’s input. The spacing is set to zero, so that all buttons are clumped together. By default, it looks like this:

Layout by default

If the amount of buttons is increased, the grid and window will grow too just fine; if, however, the amount of buttons is reduced, it will look like this:

Layout done wrong

Now I would like to resize the window/layout/widget so that all buttons may use the minimal space. I’ve tried various things, but all to no avail. I had a look at this and this question, as well at various threads in the Qt board, but none of them worked for me.

My layout is build as follows:

self.grid = QtGui.QGridLayout()

hBox = QtGui.QHBoxLayout()

vBox = QtGui.QVBoxLayout(self.widget)


I tried resizing it with …

# self.resize(self.sizeHint())

… and various other methods. I also tried setting the size policy of my window and grid.


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


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 when the number of buttons are changed, just process the event loop for some iterations and then resize to minimum.

It’s like :

for i in range(0, 10):


Another option 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.

Answered By – Nejat

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *