Fixed aspect ratio for a widget
-
Hello,
In one of my projects, I had as a business requirement (flawed or not, this is out of scope) to have a fixed aspect ratio on my top level (and unique) widget.
Basically, user should select 4:3 or 16:9 then widget keeps aspect ratio.
I dug into QWidget documentation and code but I didn't manage to do this nor did I find any good solution.
I tried catching the resize event to hack ratio but it linked to some unsatisfactory results, I tried the setPreferedHeightForWidth, but it's well named, it works only in one way...
I finally lost faith and got rid of that requirement but now that this forum exist, does any one know a clean, good way of doing it ?
-
Take a look at Qxt and in particular the "QxtLetterBoxWidget":http://libqxt.bitbucket.org/doc/tip/qxtletterboxwidget.html#details
-
Does "heightForWidth()":http://doc.qt.nokia.com/4.7-snapshot/qwidget.html#heightForWidth do what you need?
-
@tobias
No it does not : it fulfills only a partial use case. Depending on the actual resize (shrinking only horizontally / only vertically - growing only vertically / only horizontally), the result can produce a wrong ratio.Sorry, for not having linked the exact name, setPreferedHeightForWidth was what my mind remembered of height for width....
I'll try to make an example.
-
You will of course also need to set height for width in the size polizy, true. I have never tried it, not being the UI kind of guy, but I am pretty sure that should work.
-
Easy enough, just try to compile that
@
#include <QWidget>
#include <QApplication>
#include <QSizePolicy>class MyWidget:public QWidget { public: MyWidget():QWidget(){}; ~MyWidget(){}; virtual int heightForWidth ( int w ) const { return w*9/16;}; }; int main (int argv, char** argc) { QApplication a(argv,argc); MyWidget w; QSizePolicy qsp(QSizePolicy::Preferred,QSizePolicy::Preferred); qsp.setHeightForWidth(true); w.setSizePolicy(qsp); w.show(); a.exec(); }
@
and resize the windows : it doesn't care about aspect ratio at all...