简体   繁体   中英

Qt: display an image (QLabel) inside a QScrollArea

I am trying to display an image inside a QScrollArea located on the QMainWindow .

GUI

I want a fixed size for the image display, and scroll bars to appear if the loaded image is bigger than the QScrollArea . My problem is that when I load an image which is bigger than the QScrollArea , the image appears cut (which is ok) but no scroll bars appear on the UI.

Taking into account various recommandations from other stackoverflow questions, here is the generated code from the Qt designer:

mImageScrollArea = new QScrollArea(centralWidget);
mImageScrollArea->setObjectName(QString::fromUtf8("mImageScrollArea"));
mImageScrollArea->setGeometry(QRect(440, 0, 400, 700));
mImageScrollArea->setWidgetResizable(false);
scrollAreaWidgetContents = new QWidget();
scrollAreaWidgetContents->setObjectName(QString::fromUtf8("scrollAreaWidgetContents"));
scrollAreaWidgetContents->setGeometry(QRect(0, 0, 398, 698));
mLabel = new QLabel(scrollAreaWidgetContents);
mLabel->setObjectName(QString::fromUtf8("mLabel"));
mLabel->setGeometry(QRect(0, 0, 400, 700));
QSizePolicy sizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(mLabel->sizePolicy().hasHeightForWidth());
mLabel->setSizePolicy(sizePolicy);
mLabel->setScaledContents(true);
mImageScrollArea->setWidget(scrollAreaWidgetContents);

When an image is loaded, I display it in the label as follow:

QPixmap wPixmap = QPixmap::fromImage(mImage);


ui.mLabel->resize(wPixmap.size());
ui.mLabel->setPixmap(wPixmap);

ui.mLabel->show();

Why aren't any scrollbars showing if the image I load is bigger than the QScrollArea ?

It would be more helpful if you provide UI file content instead of generated C++ code. Anyway, it seems that scrollAreaWidgetContents doesn't have a layout. You need to add a grid layout to it in Qt Designer. After you do this, you will not need to resize label or scrollAreaWidgetContents manually. They will be resized automatically. Calling show on label is not required either, it will be visible by default (unless you have hid it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM