QT加载并显示文件夹里的图片

在现代应用程序中,图像处理和显示是非常常见的需求。Qt 是一个强大的跨平台 GUI 框架,提供了丰富的功能来处理图像。在本篇博客中,我们将介绍如何使用 Qt 加载并显示指定文件夹中的所有图片

cpp 复制代码
#include <QMainWindow>
#include <QVBoxLayout>
#include <QLabel>
#include <QDir>
#include <QPixmap>
#include <QFileInfoList>
#include <QFileInfo>
#include <QScrollArea>
#include <QWidget>

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
        // 创建一个中心小部件
        QWidget *centralWidget = new QWidget(this);
        setCentralWidget(centralWidget);

        // 创建垂直布局
        QVBoxLayout *layout = new QVBoxLayout(centralWidget);

        // 创建滚动区域
        QScrollArea *scrollArea = new QScrollArea(this);
        scrollArea->setWidgetResizable(true);
        layout->addWidget(scrollArea);

        // 创建一个容器小部件用于放置图片
        QWidget *imageContainer = new QWidget(this);
        QVBoxLayout *imageLayout = new QVBoxLayout(imageContainer);

        // 指定要加载的文件夹路径
        QString folderPath = "path/to/your/image/folder"; // 替换为你的图片文件夹路径
        QDir dir(folderPath);

        // 获取文件夹中的所有图片文件
        QStringList filters;
        filters << "*.png" << "*.jpg" << "*.jpeg" << "*.bmp" << "*.gif"; // 支持的图片格式
        dir.setNameFilters(filters);
        dir.setFilter(QDir::Files);

        QFileInfoList fileInfoList = dir.entryInfoList();

        // 加载并显示图片
        for (const QFileInfo &fileInfo : fileInfoList) {
            QLabel *imageLabel = new QLabel(this);
            QPixmap pixmap(fileInfo.absoluteFilePath());
            imageLabel->setPixmap(pixmap.scaled(400, 300, Qt::KeepAspectRatio, Qt::SmoothTransformation)); // 调整图片大小
            imageLayout->addWidget(imageLabel);
        }

        // 将图片容器设置为滚动区域的widget
        scrollArea->setWidget(imageContainer);
    }
};

#include <QApplication>

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    MainWindow w;
    w.resize(800, 600);
    w.show();
    return a.exec();
}
相关推荐
jzlhll12310 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin
W.D.小糊涂10 小时前
gpu服务器安装windows+ubuntu24.04双系统
c语言·开发语言·数据库
用头发抵命10 小时前
Vue 3 中优雅地集成 Video.js 播放器:从组件封装到功能定制
开发语言·javascript·ecmascript
似水明俊德10 小时前
02-C#.Net-反射-学习笔记
开发语言·笔记·学习·c#·.net
于先生吖11 小时前
Java框架开发短剧漫剧系统:后台管理与接口开发
java·开发语言
khddvbe11 小时前
C++并发编程中的死锁避免
开发语言·c++·算法
wWYy.12 小时前
STL:list
开发语言·c++
TON_G-T12 小时前
day.js和 Moment.js
开发语言·javascript·ecmascript
飞Link12 小时前
具身智能核心架构之 Python 行为树 (py_trees) 深度剖析与实战
开发语言·人工智能·python·架构
码云数智-园园13 小时前
2026 年前端开发趋势:AI 赋能、组件化与跨端一体化的深度融合
开发语言