案例:图片查看器(文件对话框与图像显示)
打开本地图片,实现缩放平移、目录遍历、旋转与状态栏信息
#这个案例做什么
写一个能日常使用的图片查看器:双击打开一张照片后,可以用滚轮无损缩放、按住鼠标拖拽平移、按 ←/→ 翻阅同一目录下的其他图片、旋转 90 度,底部状态栏实时显示尺寸、文件大小与缩放比例。它把"文件对话框 → 图像解码 → 自绘呈现 → 鼠标键盘交互"这条链路完整走了一遍,是理解 Qt 绘图与事件系统最直接的案例。
功能清单:
QFileDialog打开图片,自动识别同目录下所有可解码文件形成浏览列表;- 滚轮缩放(以鼠标位置为锚点)、按住左键拖拽平移、图像小于窗口时自动居中;
- 适应窗口 / 原始大小(1:1)/ 放大 / 缩小四种视图模式,窗口缩放时自动重算;
- 左右旋转 90°,缩放比例实时更新;
- 状态栏常驻显示:像素尺寸、文件体积、当前缩放百分比、第几张/共几张;
- 快捷键:
Ctrl+O打开、←/→翻页、Ctrl+=/Ctrl+-缩放、Ctrl+0适应窗口。
#用到的知识点
| 知识点 | 出处 |
|---|---|
QFileDialog、QMessageBox、标准对话框 | 第四篇第 1 章 对话框与交互 |
QImage / QImageReader / QPixmap | 第四篇第 5 章 绘图系统 QPainter |
QPainter::drawImage、坐标变换、抗锯齿开关 | 第四篇第 5 章 绘图系统 QPainter |
mousePressEvent / mouseMoveEvent / wheelEvent | 第三篇第 9 章 事件系统 |
QMainWindow + QToolBar + QStatusBar + QAction | 第三篇第 8 章 主窗口框架 |
QDir / QFileInfo / 目录遍历 | 第四篇第 6 章 文件与数据持久化 |
QCollator 自然排序 | 第三篇第 5 章 Qt 核心数据类型 |
QTransform 与 QImage::transformed | 第四篇第 5 章 绘图系统 QPainter |
自定义控件:重写 paintEvent 的 QWidget 子类 | 第四篇第 4 章 自定义控件与 QSS |
QShortcut / QAction 快捷键 | 第三篇第 6 章 常用基础控件 |
#项目结构
imageviewer/
├── CMakeLists.txt
└── src/
├── main.cpp
├── imageview.h
├── imageview.cpp # 自绘控件:缩放、平移、滚轮
├── mainwindow.h
└── mainwindow.cpp # 打开、遍历目录、旋转、状态栏ImageView 是一个纯粹的"显示控件",它只认识 QImage,不知道文件、不知道目录;MainWindow 负责文件 IO 与业务流程。这样分层之后,ImageView 可以直接复用到缩略图浏览器、截图工具(第六篇第 7 章)里。
cmake_minimum_required(VERSION 3.16)
project(ImageViewer LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
find_package(Qt6 REQUIRED COMPONENTS Widgets)
qt_add_executable(ImageViewer
src/main.cpp
src/imageview.cpp
src/imageview.h
src/mainwindow.cpp
src/mainwindow.h
)
target_link_libraries(ImageViewer PRIVATE Qt6::Widgets)
if(MSVC)
target_compile_options(ImageViewer PRIVATE /utf-8)
endif()#核心实现
#自绘控件 ImageView:状态只有三个量
图像显示控件的全部状态可以压缩成三个变量:源图像 m_image、缩放系数 m_scale、平移偏移 m_offset。绘制矩形由这三个量推出来,任何时候只要改了它们再 update() 即可,不需要缓存 QPixmap。先把状态设计清楚,后面的交互逻辑就是简单的算术。
// src/imageview.h
#pragma once
#include <QImage>
#include <QPoint>
#include <QWidget>
// 只负责"把一张 QImage 画出来并支持缩放平移",不关心文件
class ImageView : public QWidget
{
Q_OBJECT
public:
explicit ImageView(QWidget *parent = nullptr);
void setImage(const QImage &image);
bool hasImage() const { return !m_image.isNull(); }
qreal scaleFactor() const { return m_scale; }
void setScale(qreal scale, const QPointF &anchor = QPointF());
void zoomIn(const QPointF &anchor = QPointF());
void zoomOut(const QPointF &anchor = QPointF());
void fitToWindow();
void resetToOriginal();
signals:
void scaleChanged(qreal factor);
protected:
void paintEvent(QPaintEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
private:
QRectF imageRect() const; // 图像在窗口坐标系中的实际矩形
void clampOffset(); // 限制平移,避免图像被拖出视野
QImage m_image;
qreal m_scale = 1.0; // 1.0 = 一个图像像素对应一个逻辑像素
QPointF m_offset; // 在"居中"基础上的额外偏移
bool m_fit = true; // 是否处于适应窗口模式
bool m_panning = false;
QPoint m_lastPos;
};#绘制、缩放锚点与平移
缩放最容易做错的地方是锚点。如果只改 m_scale,图像会绕着窗口中心放大缩小,鼠标指着的地方就跑了。正确做法是让"锚点在图像中的位置"保持不变,推导出来就是下面 setScale 里那一行公式:offset' = d - (d - offset) * k,其中 d 是锚点到窗口中心的向量,k 是缩放倍数的比值。
// src/imageview.cpp
#include "imageview.h"
#include <QMouseEvent>
#include <QPainter>
#include <QWheelEvent>
#include <QtMath>
namespace {
constexpr qreal kMinScale = 0.02;
constexpr qreal kMaxScale = 64.0;
constexpr qreal kZoomStep = 1.25;
}
ImageView::ImageView(QWidget *parent)
: QWidget(parent)
{
setFocusPolicy(Qt::StrongFocus);
setCursor(Qt::OpenHandCursor);
setMouseTracking(true);
setAttribute(Qt::WA_OpaquePaintEvent); // 自己铺满背景,省一次擦除
}
void ImageView::setImage(const QImage &image)
{
m_image = image;
m_offset = QPointF();
fitToWindow();
}
QRectF ImageView::imageRect() const
{
const QSizeF s = QSizeF(m_image.size()) * m_scale;
const QPointF topLeft((width() - s.width()) / 2.0 + m_offset.x(),
(height() - s.height()) / 2.0 + m_offset.y());
return QRectF(topLeft, s);
}
void ImageView::clampOffset()
{
const QSizeF s = QSizeF(m_image.size()) * m_scale;
// 允许往外拖出 80 像素的余量,但不能把图像彻底拖没
const qreal maxX = qMax<qreal>(0.0, (s.width() - width()) / 2.0 + 80.0);
const qreal maxY = qMax<qreal>(0.0, (s.height() - height()) / 2.0 + 80.0);
m_offset.setX(qBound(-maxX, m_offset.x(), maxX));
m_offset.setY(qBound(-maxY, m_offset.y(), maxY));
}
void ImageView::setScale(qreal scale, const QPointF &anchor)
{
if (m_image.isNull()) return;
const qreal s = qBound(kMinScale, scale, kMaxScale);
if (qFuzzyCompare(s, m_scale)) return;
const QPointF center(width() / 2.0, height() / 2.0);
const QPointF a = anchor.isNull() ? center : anchor;
const QPointF d = a - center; // 锚点到中心的向量
const qreal k = s / m_scale; // 本次缩放的倍数
m_scale = s;
m_offset = d - (d - m_offset) * k; // 保证锚点下的图像像素不动
m_fit = false;
clampOffset();
emit scaleChanged(m_scale);
update();
}
void ImageView::zoomIn(const QPointF &anchor) { setScale(m_scale * kZoomStep, anchor); }
void ImageView::zoomOut(const QPointF &anchor) { setScale(m_scale / kZoomStep, anchor); }
void ImageView::fitToWindow()
{
if (m_image.isNull()) return;
const QSizeF s = QSizeF(m_image.size());
if (s.isEmpty()) return;
m_scale = qMin(width() / s.width(), height() / s.height());
m_offset = QPointF();
m_fit = true;
emit scaleChanged(m_scale);
update();
}
void ImageView::resetToOriginal()
{
if (m_image.isNull()) return;
m_scale = 1.0;
m_offset = QPointF();
m_fit = false;
emit scaleChanged(m_scale);
update();
}
void ImageView::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.fillRect(rect(), QColor(32, 32, 36));
if (m_image.isNull()) {
p.setPen(QColor(150, 150, 160));
p.drawText(rect(), Qt::AlignCenter,
QStringLiteral("用 Ctrl+O 打开一张图片"));
return;
}
// 缩小显示时开启平滑,放大时关掉才能看到真实像素
p.setRenderHint(QPainter::SmoothPixmapTransform, m_scale < 1.0);
p.drawImage(imageRect(), m_image);
}
void ImageView::wheelEvent(QWheelEvent *event)
{
if (m_image.isNull()) { QWidget::wheelEvent(event); return; }
// angleDelta 一般是一格的 120,用指数函数得到平滑的连续缩放
const qreal factor = std::pow(1.0015, event->angleDelta().y());
setScale(m_scale * factor, event->position());
event->accept();
}
void ImageView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_panning = true;
m_lastPos = event->pos();
setCursor(Qt::ClosedHandCursor);
event->accept();
return;
}
QWidget::mousePressEvent(event);
}
void ImageView::mouseMoveEvent(QMouseEvent *event)
{
if (!m_panning) { QWidget::mouseMoveEvent(event); return; }
m_offset += QPointF(event->pos() - m_lastPos);
m_lastPos = event->pos();
m_fit = false;
clampOffset();
update();
event->accept();
}
void ImageView::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && m_panning) {
m_panning = false;
setCursor(Qt::OpenHandCursor);
event->accept();
return;
}
QWidget::mouseReleaseEvent(event);
}
void ImageView::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
// 适应模式下窗口变了要重算,否则会留白或溢出
if (m_fit) fitToWindow();
else { clampOffset(); update(); }
}QWidget::wheelEvent(event) / mouseMoveEvent(event) 在基类里是 protected 且可调用的虚函数,调用它相当于"我不处理,交给默认实现"。
#主窗口:打开文件并建立浏览列表
打开一张图之后要能翻页,就要知道"同目录下还有哪些可解码的文件"。做法是拿到文件的 QFileInfo::absolutePath(),用 QDir::entryInfoList 过滤一遍后缀,再用 QCollator 做自然排序——否则 10.jpg 会排在 2.jpg 前面。
// src/mainwindow.cpp(核心片段,完整类定义见下)
#include "mainwindow.h"
#include "imageview.h"
#include <QAction>
#include <QCollator>
#include <QDir>
#include <QFileDialog>
#include <QImageReader>
#include <QLabel>
#include <QMessageBox>
#include <QStatusBar>
#include <QToolBar>
#include <QTransform>
namespace {
QStringList imageFilters()
{
QStringList out;
for (const QByteArray &format : QImageReader::supportedImageFormats())
out << QStringLiteral("*.") + QString::fromLatin1(format.toLower());
return out;
}
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, m_view(new ImageView(this))
{
setCentralWidget(m_view);
buildActions();
buildStatusBar();
resize(900, 640);
connect(m_view, &ImageView::scaleChanged,
this, [this](qreal) { updateStatusBar(); });
}
void MainWindow::buildActions()
{
auto *tb = addToolBar(QStringLiteral("主工具栏"));
tb->setMovable(false);
auto *open = new QAction(QStringLiteral("打开"), this);
open->setShortcut(QKeySequence::Open);
connect(open, &QAction::triggered, this, &MainWindow::openFile);
tb->addAction(open);
auto *prev = new QAction(QStringLiteral("上一张"), this);
prev->setShortcut(QKeySequence(Qt::Key_Left));
connect(prev, &QAction::triggered, this, [this] { step(-1); });
tb->addAction(prev);
auto *next = new QAction(QStringLiteral("下一张"), this);
next->setShortcut(QKeySequence(Qt::Key_Right));
connect(next, &QAction::triggered, this, [this] { step(1); });
tb->addAction(next);
tb->addSeparator();
auto *zoomIn = new QAction(QStringLiteral("放大"), this);
zoomIn->setShortcut(QKeySequence::ZoomIn);
connect(zoomIn, &QAction::triggered, this, [this] { m_view->zoomIn(); });
tb->addAction(zoomIn);
auto *zoomOut = new QAction(QStringLiteral("缩小"), this);
zoomOut->setShortcut(QKeySequence::ZoomOut);
connect(zoomOut, &QAction::triggered, this, [this] { m_view->zoomOut(); });
tb->addAction(zoomOut);
auto *fit = new QAction(QStringLiteral("适应窗口"), this);
fit->setShortcut(QKeySequence(Qt::ControlModifier | Qt::Key_0));
connect(fit, &QAction::triggered, m_view, &ImageView::fitToWindow);
tb->addAction(fit);
auto *actual = new QAction(QStringLiteral("原始大小"), this);
actual->setShortcut(QKeySequence(Qt::ControlModifier | Qt::Key_1));
connect(actual, &QAction::triggered, m_view, &ImageView::resetToOriginal);
tb->addAction(actual);
tb->addSeparator();
auto *rotL = new QAction(QStringLiteral("左转 90°"), this);
connect(rotL, &QAction::triggered, this, [this] { rotate(-90); });
tb->addAction(rotL);
auto *rotR = new QAction(QStringLiteral("右转 90°"), this);
connect(rotR, &QAction::triggered, this, [this] { rotate(90); });
tb->addAction(rotR);
}
void MainWindow::openFile()
{
const QString filter =
QStringLiteral("图片文件 (%1);;所有文件 (*)")
.arg(imageFilters().join(QLatin1Char(' ')));
const QString path = QFileDialog::getOpenFileName(
this, QStringLiteral("打开图片"), m_lastDir, filter);
if (path.isEmpty()) return;
openPath(path);
}
void MainWindow::openPath(const QString &path)
{
m_lastDir = QFileInfo(path).absolutePath();
buildFileList(path);
loadFile(path);
}
void MainWindow::buildFileList(const QString &file)
{
const QFileInfo fi(file);
QDir dir(fi.absolutePath());
QStringList filters;
for (const QByteArray &format : QImageReader::supportedImageFormats())
filters << QStringLiteral("*.") + QString::fromLatin1(format);
m_files.clear();
const QFileInfoList list = dir.entryInfoList(filters, QDir::Files, QDir::Name);
for (const QFileInfo &item : list)
m_files << item.absoluteFilePath();
// 自然排序:img2 排在 img10 前面,而不是字典序
QCollator collator;
collator.setNumericMode(true);
collator.setCaseSensitivity(Qt::CaseInsensitive);
std::sort(m_files.begin(), m_files.end(), collator);
m_index = m_files.indexOf(fi.absoluteFilePath());
}#解码、旋转与状态栏
旋转这一步有个必须注意的点:永远从原始图像旋转。m_source 保存解码后未旋转的图,每次旋转都由它重新变换;如果拿上一次的结果继续转,四次 90° 之后不但会累积插值误差,JPEG 还会重新编码损失画质。
bool MainWindow::loadFile(const QString &path)
{
QImageReader reader(path);
reader.setAutoTransform(true); // 处理手机照片的 EXIF 方向
const QImage image = reader.read();
if (image.isNull()) {
QMessageBox::warning(this, QStringLiteral("无法打开"),
QStringLiteral("%1\n%2").arg(path, reader.errorString()));
return false;
}
m_source = image;
m_rotation = 0;
m_view->setImage(m_source);
setWindowTitle(QStringLiteral("%1 — 图片查看器").arg(QFileInfo(path).fileName()));
updateStatusBar();
return true;
}
void MainWindow::rotate(int degrees)
{
if (m_source.isNull()) return;
m_rotation = (m_rotation + degrees + 360) % 360;
QTransform t;
t.rotate(m_rotation);
const QImage rotated =
m_source.transformed(t, Qt::SmoothTransformation);
m_view->setImage(rotated); // fitToWindow 在 setImage 内部调用
}
void MainWindow::step(int delta)
{
if (m_files.isEmpty()) return;
const int count = m_files.size();
m_index = (m_index + delta + count) % count; // 循环翻阅
loadFile(m_files.at(m_index));
}
void MainWindow::buildStatusBar()
{
m_status = new QLabel(this);
m_status->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
statusBar()->addPermanentWidget(m_status, 1);
}
void MainWindow::updateStatusBar()
{
if (m_source.isNull()) { m_status->clear(); return; }
const qint64 bytes = QFileInfo(m_files.value(m_index)).size();
const QString sizeText = bytes >= 1024 * 1024
? QString::number(bytes / 1024.0 / 1024.0, 'f', 1) + QStringLiteral(" MB")
: QString::number(bytes / 1024.0, 'f', 0) + QStringLiteral(" KB");
m_status->setText(QStringLiteral("%1 × %2 | %3 | 缩放 %4% | 第 %5/%6 张")
.arg(m_source.width())
.arg(m_source.height())
.arg(sizeText)
.arg(qRound(m_view->scaleFactor() * 100))
.arg(m_index + 1)
.arg(m_files.size()));
}对应的头文件与入口:
// src/mainwindow.h
#pragma once
#include <QImage>
#include <QMainWindow>
#include <QStringList>
class ImageView;
class QLabel;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
public slots:
// 直接打开指定路径(供命令行参数、拖拽、最近文件菜单使用)
void openPath(const QString &path);
private:
void buildActions();
void buildStatusBar();
void buildFileList(const QString &file);
bool loadFile(const QString &path);
void rotate(int degrees);
void step(int delta);
void updateStatusBar();
ImageView *m_view = nullptr;
QLabel *m_status = nullptr;
QImage m_source; // 未旋转的原始图像
int m_rotation = 0;
QStringList m_files; // 同目录图片列表
int m_index = -1;
QString m_lastDir = QStringLiteral(".");
};// src/main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setApplicationName(QStringLiteral("ImageViewer"));
MainWindow w;
w.show();
// 命令行传入路径时直接打开,方便在系统里设置"打开方式"
if (argc > 1) {
const QString path = QString::fromLocal8Bit(argv[1]);
if (QFileInfo::exists(path))
w.openPath(path);
}
return app.exec();
}把"弹对话框选文件"和"按路径打开"拆成两个函数,是很实用的分工:openFile() 只负责交互,openPath() 只负责加载。后面的练习里做拖拽打开、最近文件列表时,都只需要调用后者。
#关键细节与踩坑
1. 手机照片躺倒了:EXIF 方向。 相机拍摄的照片在 EXIF 里记录了 Orientation 标记,很多手机竖拍的照片实际存储是横向的,Windows/Linux 上直接用 QImage(path) 读会躺倒。QImageReader::setAutoTransform(true) 会按标记自动旋转。另外 QPixmap::fromImage 不会再做这件事,所以变换必须在解码阶段完成。
2. 打开一张 8000×6000 的图,界面卡住两三秒。 QImageReader::read() 是同步解码,放在主线程就会卡 UI。两种解耦办法:一是先问尺寸再缩略解码,reader.setScaledSize() 让解码器直接输出小图,只有用户放大到 100% 时才重新完整解码;二是把解码丢到 QThreadPool/工作线程(第四篇第 8 章),解完通过信号把 QImage 传回主线程——QImage 是隐式共享的,跨线程传值几乎零成本。
3. 高 DPI 下截图/导出尺寸对不上。 width() 返回的是逻辑像素,屏幕实际物理像素要乘 devicePixelRatioF()。本案例绘制时用逻辑坐标没问题,但如果你想"把当前视图导出成 PNG",grab() 得到的 QPixmap 已经是物理像素大小,导出前要么接受这个尺寸,要么显式 pixmap.setDevicePixelRatio(1)。
4. 滚轮缩放时图像会"跳"。 只改 m_scale 会以窗口中心为锚,鼠标底下的像素就跑了。修正公式是 offset' = d - (d - offset) * k(d 为锚点到中心向量,k 为缩放倍数比)。另外 event->angleDelta().y() 在不同鼠标/触摸板上量级差异很大,用 std::pow(1.0015, delta) 做指数映射比固定乘 1.25 平滑得多,也能兼容触控板的像素级滚动。
5. 缩小看细节时糊成一团,放大时又全是插值。 QPainter::SmoothPixmapTransform 不是越开越好:缩小时必须开,否则出现摩尔纹;放大到 400% 想看真实像素时必须关。本案例用 m_scale < 1.0 自动切换。同理 Qt::SmoothTransformation 用于旋转,重复旋转要回到 m_source,不要在结果上叠。
6. 目录遍历的顺序不对、中文文件名排序奇怪。 QDir::Name 是字典序,img10.jpg 会排在 img2.jpg 前面。用 QCollator::setNumericMode(true) 得到自然排序,它同时能按当前区域设置正确处理中文(拼音/笔画),std::sort 可以直接把 QCollator 当比较器用(它重载了 operator())。
#还能怎么扩展
- 缩略图侧栏:左侧放一个
QListWidget,图标模式 +setIconSize,用QImageReader::setScaledSize批量生成缩略图,配合Qt::Async的QtConcurrent::mapped并行解码。 - 拖拽打开:
setAcceptDrops(true),重写dragEnterEvent(检查mimeData()->hasUrls())和dropEvent(取urls().first().toLocalFile()),十几行就能支持把图片拖进窗口。 - 幻灯片播放:一个
QTimer每 3 秒step(1),再加一个全屏切换(showFullScreen()+ 隐藏工具栏),就是最简单的演示模式。 - 缩略图缓存:用
QCache<QString, QPixmap>缓存已解码的缩略图,避免来回翻页反复解码;配合QAbstractListModel就能改成QListView(第四篇第 2 章)。 - 简单编辑:加"裁剪"(
QImage::copy一个QRect)与"另存为"(QImage::save,JPEG 可传 quality 参数),注意保存前要把m_rotation的变换烧进像素。
#小结
- 图像显示控件的状态可以压缩成"图像 + 缩放 + 平移"三元组,绘制矩形由它们推导,改完
update()即可,不需要缓存QPixmap。 - 缩放必须处理锚点:
offset' = d - (d - offset) * k,否则鼠标底下的内容会跑掉。 - 解码要走
QImageReader而不是QImage(path):能拿errorString()给用户看,能setAutoTransform处理 EXIF,能setScaledSize避免大图卡 UI。 - 目录浏览列表用
QDir::entryInfoList+QCollator自然排序;记住当前索引才能翻页。 - 旋转、裁剪这类有损变换一定从原始图像重算,不要在结果上叠加。
SmoothPixmapTransform只在缩小时开启;放大到 1:1 以上要关掉才能看到真实像素。
#练习
- 增加"另存为"功能:
QFileDialog::getSaveFileName选择路径,按后缀调用QImage::save,JPEG 时弹出一个QInputDialog让用户输入质量(1–100),并在状态栏给出保存结果的反馈。 - 实现拖拽打开:重写
dragEnterEvent/dragMoveEvent/dropEvent,支持一次拖入多张图片(拖入多张时把第一张显示出来,其余加入浏览列表m_files)。 - 加一个"缩放锁定"按钮:开启后翻页时保持当前缩放比例与偏移量不变(提示:
setImage()里判断锁定标志,不调用fitToWindow())。 - 增加鼠标滚轮 +
Ctrl切换行为:不按Ctrl时滚轮上下滚动图像(改变m_offset.y()),按住Ctrl才是缩放;需要在wheelEvent里检查event->modifiers()。