Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take Screenshot of QML application without QQuickView

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
    } 

    //...
}
like image 236
user3296301 Avatar asked Feb 11 '14 08:02

user3296301


2 Answers

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;
  }
}
like image 54
Pavel Strakhov Avatar answered Jan 04 '23 12:01

Pavel Strakhov


You can use the QObject *obj, QEvent *ev to take screenshot as well.

Main.cpp

QObject *objekt = engine.rootObjects().first();
classObj->root_object = objekt;
app.installEventFilter(classObj);

classObj.h

QObject *root_object = nullptr;
bool eventFilter(QObject *obj, QEvent *ev);

classObj.cpp

bool classObj::eventFilter(QObject *obj, QEvent *ev)
{
    QString dateInterval = QString::number(QDateTime::currentSecsSinceEpoch());

    QDir dir("Screenshots");
    if(!dir.exists())
        dir.mkpath(".");

    if(ev->type() == QEvent::MouseButtonPress) {
        QQuickWindow *window   = qobject_cast<QQuickWindow *>(root_object);
        window->grabWindow().save("Screenshots/Screenshot-"+dateInterval+".png");
    }
    return QObject::eventFilter(obj, ev);
}

this will take screenshot whenever some event happenes.

like image 34
Jimit Rupani Avatar answered Jan 04 '23 14:01

Jimit Rupani