Qt + VS2017 创建一个简单的图片加载应用程序

简介:

本文介绍了如何使用Qt创建一个简单的图片加载应用程序。该应用程序可以打开图片文件并在界面上显示选定的图片,并保存用户上次选择的图片路径。

1. 创建项目:

首先,在VS中创建一个新的Qt Widgets应用程序项目,并命名为LoadImageApp。

2. 编写界面文件:

在Qt Designer中设计应用程序的界面,添加一个按钮用于打开图片文件,一个文本框用于显示图片路径,以及一个标签用于显示图片内容。

3. 实现应用程序逻辑:

接下来,在LoadImageApp类的实现文件LoadImageApp.cpp中,编写如下代码:

cpp 复制代码
#include "LoadImageApp.h"
#include <QSettings>
#include <QStandardPaths>
#include <memory>
#include <QFileDialog>
#include <QPixmap>

LoadImageApp::LoadImageApp(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
}

LoadImageApp::~LoadImageApp()
{}

void LoadImageApp::on_openBtn_clicked()
{
    // 读取配置文件
    QString imagePath = qApp->applicationDirPath() + "/config/Setting.ini";
    std::unique_ptr<QSettings> pSetting(new QSettings(imagePath, QSettings::IniFormat));
    QString lastPath = pSetting->value("/LastPath/imagePath").toString();
    if (lastPath.isEmpty())
    {
        lastPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
    }

    // 打开文件夹
    QString fileName = QFileDialog::getOpenFileName(this, u8"打开图片", lastPath, u8"图片(*.png *.jpg);;");
    if (fileName.isEmpty()) return;
    ui.pathEdit->setText(fileName);

    // 显示图片
    QPixmap pix;
    pix.load(fileName);
    pix = pix.scaled(ui.imageLable->size(), Qt::KeepAspectRatio);
    ui.imageLable->setScaledContents(true);
    ui.imageLable->setPixmap(pix);

    // 保存当前路径
    int lastIndexOf = fileName.lastIndexOf("/");
    QString curPath = fileName.left(lastIndexOf);
    pSetting->setValue("/LastPath/imagePath", curPath);
}

4. 代码解释:

  • on_openBtn_clicked() 槽函数响应按钮点击事件,打开文件对话框选择图片文件,并显示选定的图片。
  • 使用 QSettings 读取和保存用户上次选择的图片路径到配置文件。
  • 使用 QFileDialog 打开文件对话框选择图片文件。
  • 使用 QPixmap 加载选定的图片文件,并在界面上显示。

5. 运行结果:


5. 总结:

本文介绍了如何使用Qt创建一个简单的图片加载应用程序。通过阅读本文,您学会了如何在Qt中处理界面操作和文件操作,并将其应用到实际的应用程序开发中。

相关推荐
冬至喵喵3 分钟前
构建 CLI 的 Python 框架:Typer技术介绍
开发语言·chrome·python
AbandonForce6 分钟前
STL list
开发语言·c++
前端老石人7 分钟前
HTML 入门指南:从规范视角建立正确知识体系
开发语言·前端·html
用户8055336980311 分钟前
嵌入式Linux驱动开发——模块参数与内核调试:让模块"活"起来的魔法
qt
沐知全栈开发15 分钟前
MySQL 索引
开发语言
Albert Edison16 分钟前
【C++11】特殊类设计
开发语言·c++·单例模式·饿汉模式·懒汉模式
代码改善世界18 分钟前
【C++初阶】vector 核心接口和模拟实现
开发语言·c++
Lyyaoo.18 分钟前
【设计模式】工厂模式
java·开发语言·设计模式
宵时待雨33 分钟前
C++笔记归纳20:智能指针
开发语言·c++·笔记
jinanwuhuaguo33 分钟前
OpenClaw 2026.4.5 深度解读
android·开发语言·人工智能·kotlin·openclaw