How to resize QWidget in a layout while aligning it to the center and maintaining aspect ratio

StackOverflow https://stackoverflow.com/questions/10953479

سؤال

Ok, so I'd like to display an image with qt where the image resizes with the browser and maintains the aspect ratio while also remaining centered in the window. I can get the resizing with aspect ratio to work correctly, but when I align it with Qt::AlignCenter, the qwidget no longer resizes (remains a fixed size). So basically, I can get either option to work but not together.

A good example of what I'm trying to do would be the imshow() function in matlab. This resizes the image while maintaining the aspect ratio and also centering the image in the window. The code I have is soemthing like this:

void roilayout::resizeEvent(QResizeEvent *event)
{
    QSize p(roiview->refimage->size());
    p.scale(roiview->view->size(), Qt::KeepAspectRatio);
    roiview->view->resize(p);   
}

and in the constructor:

roiview = new roiwindow;
roiview->view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
roiview->view->setCursor(Qt::CrossCursor);
roiview->view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
roiview->view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

QHBoxLayout *layoutContainer = new QHBoxLayout;
layoutContainer->addWidget(roiview->view);
setLayout(layoutContainer);

I searched google and couldnt find anything. Also asked a similar question a little while back but from the answers it appears I didn't ask the question clearly enough. Thanks.

هل كانت مفيدة؟

المحلول

A couple of things: First it would be helpful to know what type of control "view" is. Also, I don't think you should need to resize the child control "view" (whatever type it is) within the parent's resizeEvent() callback.

A better solution might be to set the sizeHint policy on the child widget to automatically expand.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top