How to programatically resize a QMainWindow to its minimum size

sashoalm picture sashoalm · Jan 8, 2012 · Viewed 9.3k times · Source

When I have a QMainWindow with a grid layout, when resizing it with the mouse, it won't go below some minimum size that's necessary for all the controls in it to show properly. In my app I sometimes programatically hide controls, but then the window remains the same size and the rest of the controls look spread out, with too much space between them. I end up resizing the dialog manually so it doesn't look ugly.

Can I programatically set the dialog's vertical size to this minimum I get when manually resizing after I've hidden controls in it?

Answer

wesanyer picture wesanyer · May 24, 2016

I have found that resizing the centralWidget in the QMainWindow then resizing the QMainWindow itself does the trick. In other words:

from PyQt4 import QtGui
class MyMainWindow(QtGui.QMainWindow):
    def __init__(self):
        # define some widgets and stuff
    def whenWidgetsAreHidden(self):
        # this method should be triggered when you hide your widgets
        self.centralWidget.adjustSize()
        self.adjustSize()

Note that there are other widgets in the QMainWindowLayout. Per this image from the Qt Documentation, there are also Dock Widgets and other stuff that could be present. I only use the centralWidget so this solution works for me.

QMainWindow Layout