views:

2435

answers:

3

How is it possible to maintain widgets aspect ratio in Qt and what about centering the widget?

+2  A: 

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().

dF
This seems like the right answer but I have to look into it when I'm at work and maybe give a more detailed answer after I've done that.
Bleadof
+4  A: 
Bleadof
You are talking about subclassing `QLayout`, but the functions you quote are from `QLayoutItem`, which just calls the corresponding functions from `QWidget`. So what can inheriting `QLayout` give you that `QWidget` itself can't?
I'm going to get back on this when I actually have time test it...
Bleadof
+1  A: 

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().

Have you actually tried this?-)
Bleadof
Yes. You need to set a `sizePolicy` that `hasHeightForWidth() == true`, and the layout will often give the widget more width or height that it asks for, but that's the layout trying to satisfy the constraints. You will get the same effect with the `QLayoutItem` solution, as they're equivalent (cf. `QWidgetLayoutItem`).