Qt ScrollArea
-
Hello, gurus! I am making a simple project *** for loading large images with scrolling. This version does not work. I know Qt examples and other examples, based on dynamically placing an QLabel i widget n a scroll area. For my task, I need to work with a QLabel placed in a scroll area in Qt designer UI. Has anyone managed to achieve scrolling in similiar project version?
*** Step-by-Step Guide
Design the UI in Qt Designer:
Open Qt Designer and create a new MainWindow form.
Drag a QScrollArea widget from the widget box and place it in the
central widget area.
Drag a QLabel widget and place it inside the QScrollArea.
Set the QLabel’s objectName to imageLabel.
Set the QScrollArea’s objectName to scrollArea.
Ensure the QScrollArea’s widgetResizable property is set to true.
Ensure the QLabel’s scaledContents property is set to true.
Save the UI File:
Save the form as mainwindow.ui.
Generate the UI Header File:
Use the uic tool to generate the header file from the .ui file:
uic mainwindow.ui -o ui_mainwindow.hCreate the Main Application Code:
Create a new C++ source file (e.g., main.cpp) and include the generated header file.
Example Code
#include <QApplication>
#include <QMainWindow>
#include <QScrollArea>
#include <QLabel>
#include "ui_mainwindow.h"class MainWindow : public QMainWindow {
Q_OBJECTpublic:
MainWindow(QWidget *parent = nullptr) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);// Load an image and set it to the QLabel QPixmap pixmap("path/to/your/image.jpg"); ui->imageLabel->setPixmap(pixmap); } ~MainWindow() { delete ui; }
private:
Ui::MainWindow *ui;
};int main(int argc, char *argv[]) {
QApplication app(argc, argv);MainWindow mainWindow; mainWindow.show(); return app.exec();
}
-
Hi,
Did you just put the QLabel there ? If so that is your issue, you have to use a layout to add it to the QWidget that is automatically set on the QScrollArea.
Other solution: creat the QLabel in the constructor and set it on the QScrollArea to replace the QWidget.
-
You are right, the layout in "scrollAreaWidgetContents" solved the problem. Thank you very much.
-