Can I make a QMainWindow with a grid layout resize only horizontally but not vertically?
I want its vertical size to be the minimum needed to hold all the buttons/line edits.
Yes you can. As a QMainWindow inherits from QWidget, use the QWidget size policy settings to only allow resizing in the horizontal direction.
If working in Qt Designer, set the vertical size policy to be fixed, and the minimum height to be your desired height. In code:
QMainWindow *mainWindow = new QMainWindow();
mainWindow->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
Be cautious using absolute fixed size as the controls might need to still grow vertically (e.g. the user sets a high DPI font on their desktop).
I saw another way in one of the examples in a book called "C++ GUI Programming with Qt 4". They did it with
setFixedHeight(sizeHint().height());
code below works fine
setFixedHeight(sizeHint().height());
but code below
QMainWindow *mainWindow = new QMainWindow();
mainWindow->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
doesn't work because wrong parameter is passed to the function setSizePolicy
. This function has two forms, one of which requires QSizePolicy::Policy
and the other one requires QSizePolicy
but QSizePolicy::Expanding
is neither a QSizePolicy
nor a QSizePolicy::Policy
.