lundi 30 mars 2015

Fixed Aspect Ratio For QT Windows

I have read many questions about this topic but all I have found are either unanswered, do not do what I want, or simply do not work.


My problem is that of maintaining a height to width ratio while resizing my main window. So far I have seen propositions to override 'QLayout' and use 'heightForWidth' to perform the deed, to use the 'resizeEvent' call back to change the size hint, and to use the 'resizeEvent' call back to resize the window.


The first two options I mentioned only work in the examples for dragging width; I want a user to be able to drag width or height. The second of the two I attempted to adapt for my purposes but it causes my code to crash (the first relies on the 'heightForWidth' function and I cannot find a 'widthForHeight' function {The comments in this thread support my conclusion: How to maintain widgets aspect ratio in Qt?}). The third option was what I originally attempted but has a lot of bugs: most of the time the window snaps back to its original size, having rapidly transitioned between that and where it should be while dragging the border with the mouse.


The attempt which causes a crash:



void window::resizeEvent(QResizeEvent *event)
{
//window::resizeEvent(event); causes crash

if ((this->width() * 5 / 8) > (this->height() + 1)
|| (this->width() * 5 / 8) < (this->height() - 1))
{
updateGeometry();
}
}

QSize window::sizeHint() const
{
QSize s = size();
if (lastWidth != s.width())
{
s.setHeight((s.width()*5)/8);
//s.setWidth(window::sizeHint().width());
}
else if (lastHeight != s.height())
{
s.setWidth((s.height()*8)/5);
//s.setHeight(window::sizeHint().height());
}
return s;
}


The attempt which has bugs:



void window::resizeEvent(QResizeEvent *)
{
//If the window does not have the correct aspect ratio
//This should be false if this function caused the resize event,
// preventing a loop
if ((this->width() * 5 / 8) > (this->height() + 1)
|| (this->width() * 5 / 8) < (this->height() - 1))
{
int currentHeight = this->height();
int currentWidth = this->width();

//Change the dimension the user did not to match the user's change.
if (lastWidth != currentWidth)
{
lastWidth = currentWidth;
currentHeight = currentWidth * 5/8;
lastHeight = currentHeight;
}
else
{
lastHeight = currentHeight;
currentWidth = currentHeight * 8/5;
lastWidth = currentWidth;
}

//update the change
this->resize(currentWidth,currentHeight);
}
}

Aucun commentaire:

Enregistrer un commentaire