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

发布时间:2023-05-18 18:00

若该文为原创文章,未经允许不得转载
原博主博客地址: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

        下载地址: http://download.csdn.net/download/qq21497936/10226423
 

效果截图

\"Qt实用技巧:截屏功能的实现_第1张图片\"

 

\"Qt实用技巧:截屏功能的实现_第2张图片\"

 

\"Qt实用技巧:截屏功能的实现_第3张图片\"

 

核心代码

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

 
原博主博客地址: https://blog.csdn.net/qq21497936
原博主博客导航: https://blog.csdn.net/qq21497936/article/details/102478062
本文章博客地址: https://blog.csdn.net/qq21497936/article/details/79177272

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号