最近有个需求需要更新设备的ui文档。但是用手机拍照又是那么不尽人意,于是想到用Qt写个截屏功能,于是先在ubuntu16.0.4中写个测试例子,代码如下:

void ScreenShort::screenShortOne()
{
    QScreen *screen = QGuiApplication::primaryScreen();
    QString filePathName = "full-"+QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss-zzz")+".jpg";

    QString filePath ="/home/awapp/screenshort";
    QString absFileName = filePath + "/"+filePathName;

    QDir dir(filePath);

    if( !dir.exists() )
    {
        if( dir.mkpath(filePath) )
        {
            qDebug()<<"create dir:"<<filePath;
        }
    }


    if(!screen->grabWindow(0).save(absFileName, "jpg"))
    {
        qDebug()<<"save full screen failed";
    }

    qDebug()<<"save file Path="<<absFileName;
}

该例子在ubuntu下运行丝毫没有问题,于是移植到设备上,但是截图失败,并且打印了如下信息:

QQuickWindow::grabWindow: scene graph already in Use QQuickWindow::grabWindow() instead。

于是查阅了大量资料终于找到解决办法。代码如下:

screencapture.h

#ifndef SCREENSHOT_H
#define SCREENSHOT_H

#include <QObject>

class QString;
class QQuickWindow;

class ScreenCapture : public QObject
{
    Q_OBJECT
public:
    explicit ScreenCapture (QQuickWindow *parent = 0);

public slots:
    void capture () const;

private:
    QQuickWindow *currentWindow;
};

#endif // SCREENSHOT_H

screenshort.cpp

#include <QPixmap>
#include <QQuickView>
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include "screencapture.h"

ScreenCapture::ScreenCapture(QQuickWindow *currentWindow) :
    QObject(0), currentWindow (currentWindow)
{
}

void ScreenCapture::capture () const
{
    QString filePathName = "full-"+QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss-zzz")+".jpg";

    QString filePath ="/home/awapp/screenshort";
    QString absFileName = filePath + "/"+filePathName;

    QDir dir(filePath);

    if( !dir.exists() )
    {
        if( dir.mkpath(filePath) )
        {
            qDebug()<<"create dir:"<<filePath;
        }
    }
    qDebug()<<"save file Path="<<absFileName;
    QImage p = currentWindow->grabWindow();
    bool kk = p.save (absFileName);
    qDebug () << kk;
}

用法:


    QObject      *topLevel = engine.rootObjects().value(0);
    QQuickWindow *window   = qobject_cast<QQuickWindow *>(topLevel);

    ScreenCapture launcher (window);

    engine.rootContext()->setContextProperty("ScreenShot", &launcher);

    window->show();