若该文为原创文章,未经允许不得转载

各位读者,知识无穷而人力有穷,要么改需求,要么找专业人士,要么自己研究

红胖子(红模仿)的博文大全:开发技术集合(包含Qt实用技术、树莓派、三维、OpenCV、OpenGL、ffmpeg、OSG、单片机、软硬结合等等)持续更新中…(点击传送门)

​​Qt开发专栏:实用技巧(点击传送门)​​


需求

        写一个截屏模块。


Demo


        下载地址:​​




效果截图

Qt实用技巧:截屏功能的实现_Qt截屏


Qt实用技巧:截屏功能的实现_javascript_02


Qt实用技巧:截屏功能的实现_sed_03


核心代码


初始化截屏窗口代码



// 设置无边框
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
// 激活并全屏
setWindowState(Qt::WindowActive | Qt::WindowFullScreen);
// 抓取当前屏幕图片,使用QPixmap,Qt5.9.3会有提示信息
// this function is deprecated, use QScreen::grabWindow() instead.
// Defaulting to primary screen.
_pixmapScreen = QPixmap::grabWindow(QApplication::desktop()->winId());
_screenWidth = _pixmapScreen.width();
_screenHeight = _pixmapScreen.height();

绘制代码



QPainter painter(this);
// 背景刷图
QColor shadowColor = QColor(0, 0, 0, 100);
painter.drawPixmap(0, 0, _pixmapScreen);
painter.fillRect(_pixmapScreen.rect(), shadowColor);
if(_bPressed)
{
QRect selectedRect(_pointStart, _pointEnd);
// QRect允许负值,使用mormalized转化为正值
selectedRect = selectedRect.normalized();
// 截图黑框
painter.setPen(QPen(Qt::black, 2));
painter.drawRect(selectedRect);
// 截图的rect,再次填充
_pixmapCaptrueScreen = _pixmapScreen.copy(selectedRect);
painter.drawPixmap(selectedRect.topLeft(), _pixmapCaptrueScreen);
}



鼠标操作代码




void CaptureScreen::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
_bPressed = true;
_pointStart = event->pos();
_pointEnd = event->pos();
update();
}
}

void CaptureScreen::mouseMoveEvent(QMouseEvent *event)
{
_pointEnd = event->pos();
update();
}

void CaptureScreen::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
_bPressed = false;
_pointEnd = event->pos();
update();
emit capturePixmapFnished(true, _pixmapCaptrueScreen);
close();
}else{
emit capturePixmapFnished(true, _pixmapCaptrueScreen);
close();
}
}