QLabel showing an image inside a QScrollArea

只谈情不闲聊 提交于 2019-12-05 07:18:33
Timothy Pitt

I know this is an old post - but in case you or anyone is still having a problem, it might help to set QScrollArea::widgetResizable to false.

At least, when I tried a similar thing, my vertical scrollbar was always disabled (even though I set the size of the scrollable widget to have a height larger than the viewport) until I set this to false.

When it's true, I think it updates the size of the scrollable widget, thus the scrollbars should not be needed. This allows you to do what it does in the example I guess, and implement a stretch-to-fit function. (actually what I'm trying to do is fit to width, with just a vertical scroll bar)

Eli Hooten

Have you tried following Qt's scroll area example? If you're using a QLabel to display your image, then the use of QScrollArea is pretty much the standard way of achieving what you want. You use it like so (from the example):

 imageLabel = new QLabel;
 imageLabel->setBackgroundRole(QPalette::Base);
 imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
 imageLabel->setScaledContents(true);

 scrollArea = new QScrollArea;
 scrollArea->setBackgroundRole(QPalette::Dark);
 scrollArea->setWidget(imageLabel);
 setCentralWidget(scrollArea);

Then zooming is handled like so:

 void ImageViewer::zoomIn() { 
    scaleImage(1.25);
 }

 void ImageViewer::zoomOut() {
     scaleImage(0.8);
 }

 void ImageViewer::scaleImage(double factor)
 {
     Q_ASSERT(imageLabel->pixmap());
     scaleFactor *= factor;
     imageLabel->resize(scaleFactor * imageLabel->pixmap()->size());

     adjustScrollBar(scrollArea->horizontalScrollBar(), factor);
     adjustScrollBar(scrollArea->verticalScrollBar(), factor);

     zoomInAct->setEnabled(scaleFactor < 3.0);
     zoomOutAct->setEnabled(scaleFactor > 0.333);
 }

 void ImageViewer::adjustScrollBar(QScrollBar *scrollBar, double factor) {
     scrollBar->setValue(int(factor * scrollBar->value()
                         + ((factor - 1) * scrollBar->pageStep()/2)));
 }

You can, of course, get a better idea of what's going on by looking at the example, but that's the gist of it. I think perhaps the adjustScrollBar() function might be the most helpful thing for you.

Your last comment on the original post is correct, the QScrollArea doesn't magically notice the change in size of its contents. Look at how the example uses adjustScrollBar() to compensate for this fact.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!