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

若该文为原创文章,未经允许不得转载
原博主博客地址:https://blog.csdn.net/qq21497936
原博主博客导航:https://blog.csdn.net/qq21497936/article/details/102478062
本文章博客地址:https://blog.csdn.net/qq21497936/article/details/79177272
各位读者,知识无穷而人力有穷,要么改需求,要么找专业人士,要么自己研究

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

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

 

需求

        写一个截屏模块。

 

Demo

 

效果截图

 

 

 

核心代码

初始化截屏窗口代码
    // 设置无边框
    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();
    }
}

 
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长沙红胖子Qt(长沙创微智科)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值