How to take Screenshot of QML application without

2019-03-28 01:40发布

问题:

I want to grab screen of my QML application. But my root QML object is ApplicationWindow, so I can't use QQuickView to show it. Instead I have to use QQmlApplicationEngine. I know how to take screenshot with QQuickView (QQuickWindow::grabWindow), but don't know how to take it with QQmlApplicationEngine.

My main file:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    ApplicationData appData;
    QQmlApplicationEngine engine;
    engine.load(QUrl("qrc:///main.qml"));
    return app.exec();
}

main.qml :

import QtQuick 2.1
import QtQuick.Controls 1.1
import QtQuick.Window 2.1


ApplicationWindow {
    id: mainWindow
    width: appData.screenWidth
    height: appData.screenHeight
    visible: true

    Rectangle {
        id: mainWindowBackground
        color: "red"
        anchors.fill: parent
    } 

    //...
}

回答1:

You can use rootObjects() and cast its result to QQuickWindow:

foreach(QObject* obj, engine.rootObjects()) {
  QQuickWindow* window = qobject_cast<QQuickWindow*>(obj);
  if (window) {
    QImage image = window->grabWindow();
    qDebug() << image;
  }
}


回答2:

You can cast ApplicationWindow(QML) to QQuickWindow(C++). Then, It will be easy to take screenshot.

void ScreenShot(QQuickWindow *widget) {
    QPixmap pixmap = QPixmap::fromImage(widget->grabWindow());
    QFile f("your_name.png");
    f.open(QIODevice::WriteOnly);
    if(f.isOpen()) {
        pixmap.save(&f, "PNG");
    }