How to take Screenshot of QML application without QQuickView

前端 未结 3 848
深忆病人
深忆病人 2021-02-15 11:55

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

相关标签:
3条回答
  • 2021-02-15 12:41

    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.

    0 讨论(0)
  • 2021-02-15 12:53

    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");
        }
    
    0 讨论(0)
  • 2021-02-15 12:55

    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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题