View Full Version : (not a question) : how to make a main window resize to its contents

8th June 2012, 14:27
I spent quite a lot of time finding an answer to this question, so I decided to share the findings.
I was struck by the blinding flash of the obvious reading this thread (http://www.qtcentre.org/wiki/index.php?title=Expanding_dialog), but it seems Google has not deemed it as interresting as I do.
Besides, instead of providing a lenghty example, I decided to narrow it down to the two essential lines of code.
So here it goes:

Sometimes you may want your main window to resize to its current (dynamic) contents.
In my case I wanted my silly brickout game to resize according to its level layout :

The trick is simply to apply a fixed-size layout to the main window.

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
// trick to get the main window to resize to its contents

// rest of constructor code...

In this example I use a MainWindow straight from QT designer, but the same can be done with any hand-coded class.

Hope some people will find that useful...