How is it possible to maintain widgets aspect ratio in Qt and what about centering the widget?
Calling resize()
from within resizeEvent()
has never worked well for me -- at best it will cause flickering as the window is resized twice (as you have), at worst an infinite loop.
I think the "correct" way to maintain a fixed aspect ratio is to create a custom layout. You'll have to override just two methods, QLayoutItem::hasHeightForWidth()
and QLayoutItem::heightForWidth()
.
You don't have to implement your own layout manager. You can do with inheriting QWidget
and reimplementing
int QWidget::heightForWidth( int w ) { return w; }
to stay square. However, heightForWidth()
doesn't work on toplevel windows on X11, since apparently the X11 protocol doesn't support that. As for centering, you can pass Qt::AlignCenter
as the third parameter of QBoxLayout::addWidget()
or the fifth parameter of QGridLayout::addWidget()
.