Layouts
From qtnode
One of the most frequently asked questions is how to make widgets automatically adjust to the geometry of the window. Qt offers a simple, effective set of layout classes to address this concern. The official documentation by Trolltech is very thorough. (Qt 4.1 Qt 3.3)
Layouts and QMainWindow
A common problem people have with layouts regards the QMainWindow class. QMainWindow uses a special internal layout that is otherwise unavailable, so normal layout classes can't be directly applied to one. The correct way to use a QMainWindow is to create an ordinary QWidget and set it as the QMainWindow's central widget, and then add the layout to this widget and use it as the parent widget for all other children of the window.
For example, in the constructor of the QMainWindow subclass:
QWidget* center = new QWidget(this); QVBoxLayout* layout = new QVBoxLayout(center); setCentralWidget(center); QPushButton* button = new QPushButton(center); layout->addWidget(button);
This code snippet sets up the central widget and a vertical layout, and then it adds a push button. This push button will automatically resize to fill the window when the window is resized. (On some platforms, especially MacOS and Windows XP, the button's height won't visibly change. This is a side effect of the way these platforms render buttons in the default theme; internally, the button's geometry fills the window.) A similar technique can be used for adding layouts and widgets directly to a QMainWindow without subclassing.
Top-Level Widgets
When using a layout manager, a parent widget will automatically resize its height and width according to the size hints of its child widgets. This size is then used as a size hint for the layout containing the parent widget. Top-level widgets, then, are automatically given a reasonably appropriate size for their contents.
Top-level widgets can still have parent widgets. They have no effect over each other's layouts, but a child QDialog will be initially centered over the parent window. Top-level widgets without a parent are positioned on the screen at the whim of the window manager.
Both the size and position of top-level widgets can be overridden from their default hints using QWidget::resize() and QWidget::move() (Qt 4.1 Qt 3.3). The geometry of the system desktop can be found using QApplication::desktop() (Qt 3.3); this is most commonly useful for centering a window on the screen.