Qt实现屏幕截图小工具的完整指南
作者:小灰灰搞电子
这篇文章主要为大家详细介绍了基于Qt实现的屏幕截图工具源码,包含全屏截图和选区截图功能,文中的示例代码讲解详细,有需要的小伙伴可以参考下
一、效果展示



二、源码分享
1、mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPixmap>
#include <QScreen>
#include <QFileDialog>
#include <QClipboard>
#include <QPainter>
#include <QMouseEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
// 选区截图全屏遮罩窗口
class CaptureMask : public QWidget
{
Q_OBJECT
public:
explicit CaptureMask(QWidget *parent = nullptr);
void setScreenPix(const QPixmap &pix);
protected:
void paintEvent(QPaintEvent *) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
signals:
void captureFinished(const QPixmap &pix);
private:
QPixmap m_screenBg;
QPoint m_startPos;
QPoint m_endPos;
bool m_isDragging = false;
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
private slots:
// 全屏截图
void slotCaptureFull();
// 选区截图
void slotCaptureArea();
// 截图完成回调
void slotOnCaptureDone(const QPixmap &pix);
// 保存图片
void slotSaveImage();
// 复制到剪贴板
void slotCopyClipboard();
private:
Ui::MainWindow *ui;
QPixmap m_capturePix; // 当前截图缓存
};
#endif // MAINWINDOW_H
2、mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include <QDateTime>
CaptureMask::CaptureMask(QWidget *parent)
: QWidget(parent, Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)
{
setAttribute(Qt::WA_DeleteOnClose);
setAttribute(Qt::WA_TranslucentBackground, false);
setAutoFillBackground(false);
}
void CaptureMask::setScreenPix(const QPixmap &pix)
{
m_screenBg = pix;
QRect screenRect = QApplication::primaryScreen()->geometry();
this->setGeometry(screenRect);
this->showFullScreen();
}
void CaptureMask::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// ========== 绘制逻辑:原图在上,暗色遮罩覆盖,选区挖空 ==========
// 1. 先绘制完整原图
painter.drawPixmap(rect(), m_screenBg);
// 2. 全局绘制半透明黑色遮罩(全覆盖变暗)
QColor darkColor(0, 0, 0, 150);
painter.fillRect(rect(), darkColor);
if (m_isDragging)
{
QRect selectRect = QRect(m_startPos, m_endPos).normalized();
// 3. 在选区重新绘制原图,覆盖掉黑色遮罩,实现框内高亮
painter.drawPixmap(selectRect, m_screenBg, selectRect);
// 4. 绘制选区边框与填充
painter.setPen(QPen(QColor(0, 180, 255), 2));
painter.setBrush(QColor(0, 160, 255, 60));
painter.drawRect(selectRect);
}
}
void CaptureMask::mousePressEvent(QMouseEvent *event)
{
m_isDragging = true;
m_startPos = event->pos();
m_endPos = m_startPos;
update();
}
void CaptureMask::mouseMoveEvent(QMouseEvent *event)
{
if (!m_isDragging) return;
m_endPos = event->pos();
update();
}
void CaptureMask::mouseReleaseEvent(QMouseEvent *)
{
m_isDragging = false;
QRect rect = QRect(m_startPos, m_endPos).normalized();
QPixmap result = m_screenBg.copy(rect);
emit captureFinished(result);
this->close();
}
// ================= MainWindow =================
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("Qt6 截图工具");
this->resize(600, 450);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slotCaptureFull()
{
QScreen *screen = QApplication::primaryScreen();
m_capturePix = screen->grabWindow(0);
slotOnCaptureDone(m_capturePix);
}
void MainWindow::slotCaptureArea()
{
CaptureMask *mask = new CaptureMask(this);
QScreen *screen = QApplication::primaryScreen();
QPixmap fullPix = screen->grabWindow(0);
mask->setScreenPix(fullPix);
connect(mask, &CaptureMask::captureFinished,
this, &MainWindow::slotOnCaptureDone);
}
void MainWindow::slotOnCaptureDone(const QPixmap &pix)
{
m_capturePix = pix;
// 显示截图到label,自动缩放
ui->label_view->setPixmap(pix.scaled(ui->label_view->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
void MainWindow::slotSaveImage()
{
if (m_capturePix.isNull())
{
QMessageBox::information(this, "提示", "请先截图!");
return;
}
QString timeStr = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss");
QString path = QFileDialog::getSaveFileName(this, "保存截图",
QString("./%1.png").arg(timeStr),
"PNG图片(*.png);;JPG图片(*.jpg)");
if (!path.isEmpty())
{
m_capturePix.save(path);
QMessageBox::information(this, "成功", "图片已保存");
}
}
void MainWindow::slotCopyClipboard()
{
if (m_capturePix.isNull())
{
QMessageBox::information(this, "提示", "请先截图!");
return;
}
QApplication::clipboard()->setPixmap(m_capturePix);
QMessageBox::information(this, "成功", "截图已复制到剪贴板");
}
3、mainWindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>600</width>
<height>450</height>
</rect>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="btn_full">
<property name="text">
<string>全屏截图</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_area">
<property name="text">
<string>选区截图</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_save">
<property name="text">
<string>保存图片</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_copy">
<property name="text">
<string>复制剪贴板</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="label_view">
<property name="minimumSize">
<size>
<width>0</width>
<height>300</height>
</size>
</property>
<property name="styleSheet">
<string notr="true">border:1px solid #999;</string>
</property>
<property name="text">
<string>截图预览区域</string>
</property>
<property name="alignment">
<set>Qt::AlignmentFlag::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>btn_full</sender>
<signal>clicked()</signal>
<receiver>MainWindow</receiver>
<slot>slotCaptureFull()</slot>
<hints>
<hint type="sourcelabel">
<x>20</x>
<y>20</y>
</hint>
<hint type="destinationlabel">
<x>20</x>
<y>20</y>
</hint>
</hints>
</connection>
<connection>
<sender>btn_area</sender>
<signal>clicked()</signal>
<receiver>MainWindow</receiver>
<slot>slotCaptureArea()</slot>
<hints>
<hint type="sourcelabel">
<x>20</x>
<y>20</y>
</hint>
<hint type="destinationlabel">
<x>20</x>
<y>20</y>
</hint>
</hints>
</connection>
<connection>
<sender>btn_save</sender>
<signal>clicked()</signal>
<receiver>MainWindow</receiver>
<slot>slotSaveImage()</slot>
<hints>
<hint type="sourcelabel">
<x>20</x>
<y>20</y>
</hint>
<hint type="destinationlabel">
<x>20</x>
<y>20</y>
</hint>
</hints>
</connection>
<connection>
<sender>btn_copy</sender>
<signal>clicked()</signal>
<receiver>MainWindow</receiver>
<slot>slotCopyClipboard()</slot>
<hints>
<hint type="sourcelabel">
<x>20</x>
<y>20</y>
</hint>
<hint type="destinationlabel">
<x>20</x>
<y>20</y>
</hint>
</hints>
</connection>
</connections>
<slots>
<slot>slotCaptureFull()</slot>
<slot>slotCaptureArea()</slot>
<slot>slotOnCaptureDone(const QPixmap&)</slot>
<slot>slotSaveImage()</slot>
<slot>slotCopyClipboard()</slot>
</slots>
</ui>三、实现原理
本截图工具的核心实现依赖于 Qt6 的事件系统(Event System)和绘图系统(Painting System)。下面详细解析关键事件的工作原理:
1、Qt6 事件系统概述
Qt 采用事件驱动的编程模型,所有用户交互(鼠标点击、键盘输入、窗口重绘等)都通过事件(Event)来传递和处理。事件处理流程如下:
- 事件产生:由操作系统或 Qt 内部产生
- 事件派发:通过
QApplication::notify()派发到目标对象 - 事件过滤:可通过
installEventFilter()进行预处理 - 事件处理:目标对象的
event()方法接收并分发给特定事件处理器
2、截图工具中的关键事件详解
paintEvent - 绘图事件
void CaptureMask::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// 1. 绘制完整屏幕截图作为背景
painter.drawPixmap(rect(), m_screenBg);
// 2. 全局半透明黑色遮罩(实现变暗效果)
QColor darkColor(0, 0, 0, 150); // RGBA: 黑色,透明度150/255
painter.fillRect(rect(), darkColor);
if (m_isDragging)
{
QRect selectRect = QRect(m_startPos, m_endPos).normalized();
// 3. 选区区域重新绘制原图(挖空效果)
painter.drawPixmap(selectRect, m_screenBg, selectRect);
// 4. 绘制选区边框和半透明填充
painter.setPen(QPen(QColor(0, 180, 255), 2)); // 蓝色边框
painter.setBrush(QColor(0, 160, 255, 60)); // 浅蓝色半透明填充
painter.drawRect(selectRect);
}
}
原理说明:
paintEvent在以下情况自动触发:- 窗口首次显示
- 窗口被其他窗口遮挡后重新显示
- 调用
update()或repaint()方法 - 窗口大小改变
- 本工具中,每次鼠标移动(
mouseMoveEvent)都会调用update(),从而触发重绘 - 通过分层绘制实现选区高亮效果:
- 底层:完整屏幕截图
- 中层:全局半透明黑色遮罩(变暗效果)
- 上层:选区区域的原图(挖空效果)+ 蓝色边框
鼠标事件三部曲
mousePressEvent - 鼠标按下
void CaptureMask::mousePressEvent(QMouseEvent *event)
{
m_isDragging = true; // 开始拖拽状态
m_startPos = event->pos(); // 记录起始位置
m_endPos = m_startPos; // 初始结束位置=起始位置
update(); // 触发重绘(绘制起始点)
}
mouseMoveEvent - 鼠标移动
void CaptureMask::mouseMoveEvent(QMouseEvent *event)
{
if (!m_isDragging) return; // 非拖拽状态不处理
m_endPos = event->pos(); // 更新结束位置
update(); // 触发重绘(更新选区矩形)
}
mouseReleaseEvent - 鼠标释放
void CaptureMask::mouseReleaseEvent(QMouseEvent *)
{
m_isDragging = false; // 结束拖拽状态
// 计算标准化矩形(确保左上角到右下角)
QRect rect = QRect(m_startPos, m_endPos).normalized();
// 从原图中截取选区
QPixmap result = m_screenBg.copy(rect);
// 发射信号通知截图完成
emit captureFinished(result);
// 关闭遮罩窗口
this->close();
}
事件传递机制:
- Qt 使用
QMouseEvent封装鼠标事件信息 event->pos()返回相对于当前窗口的坐标normalized()确保矩形坐标是标准化的(左上角到右下角)
3、事件与信号槽的协同
事件处理流程
用户按下鼠标 → mousePressEvent
↓
用户拖动鼠标 → mouseMoveEvent → update() → paintEvent
↓
用户释放鼠标 → mouseReleaseEvent
↓
发射 captureFinished 信号 → MainWindow::slotOnCaptureDone
关键技术点
全屏遮罩窗口
// 窗口标志设置 Qt::Window | // 作为独立窗口 Qt::FramelessWindowHint | // 无边框 Qt::WindowStaysOnTopHint // 始终置顶 // 窗口属性 setAttribute(Qt::WA_DeleteOnClose); // 关闭时自动删除 setAttribute(Qt::WA_TranslucentBackground, false); // 不透明背景
屏幕捕获
// 获取主屏幕 QScreen *screen = QApplication::primaryScreen(); // 捕获整个屏幕(包括所有窗口) QPixmap fullPix = screen->grabWindow(0); // 0表示整个屏幕
图像处理
QPixmap::copy(const QRect &):截取指定区域QPixmap::save():保存到文件QClipboard::setPixmap():复制到剪贴板
4、Qt6 事件系统的新特性
改进的事件过滤器:Qt6 增强了事件过滤器的性能,支持更精细的事件拦截和处理。
手势事件支持:新增对触摸屏和手势的更好支持,虽然本工具未使用,但在移动端开发中很重要。
输入法事件优化:对多语言输入法的支持更加完善。
5、性能优化建议
减少不必要的重绘:
- 只在选区变化时调用
update() - 使用
update(QRect)只重绘脏区域
- 只在选区变化时调用
内存管理:
- 大尺寸截图及时释放
- 使用
QPixmapCache缓存常用图像
响应式设计:
- 在高DPI屏幕上使用
devicePixelRatio适配 - 支持多屏幕截图
- 在高DPI屏幕上使用
到此这篇关于Qt实现屏幕截图小工具的完整指南的文章就介绍到这了,更多相关Qt屏幕截图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
