其他分享
首页 > 其他分享> > 获取窗口:场景图已经在使用中

获取窗口:场景图已经在使用中

作者:互联网

I tried the code shown here: How to take ScreenShot Qt/QML

On execution I am getting the error written in the title.

My main.cpp is:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#include <QImage>
#include <QDebug>
#include "screenshot.h"
#include <QQuickView>
#include <QQmlContext>

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

    const char* drigUi = "DrigUI"; 
    qmlRegisterType <screenCapture> (drigUi, 1, 0, "ScreenShot");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

I used this capture function:

void screenCapture::capture(QString const &path) const
{
    QImage img = currentView_->grabWindow();
    img.save(path);
}

and added the following in the constructor:

currentView_ = new QQuickView;

My main.qml :

import QtQuick 2.4
import QtQuick.Window 2.2

import DrigUI 1.0

Window
{
    visible: true
    height: 370
    width: 370

    ScreenShot { id: screenShot }

    Rectangle
    {
        id: ll
        height: 30
        width: 50
        x: 180; y: 0; color: "red"
        MouseArea
        {
            anchors.fill: parent
            onClicked: screenShot.capture ("l.png")
        }
    }
}

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 (QString const &path) const;

private:
    QQuickWindow *currentWindow;
};

#endif // SCREENSHOT_H

ScreenCapture.cpp:

#include <QPixmap>
#include <QQuickView>
#include <QDebug>
#include "screenshot.h"

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

void screenCapture::capture (QString const &path) const
{
    QImage p = currentWindow->grabWindow ();
    bool kk = p.save (path);
    qDebug () << kk;
}

main.cpp:

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

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

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

    screenCapture launcher (window);

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

    window->show();

    return app.exec();
}

Now, in QML side, we can directly use

ScreenShot.capture ("/home/*****/Desktop/l.png")

anywhere we want. It works.


转自:获取窗口:场景图已经在使用中 - QQuickWindow::grabWindow: scene graph already in use - 开发者知识库 (itdaan.com)

c++ - QQuickWindow::grabWindow: scene graph already in use - Stack Overflow 

标签:main,QQuickWindow,场景,窗口,capture,获取,const,include,screenCapture
来源: https://blog.csdn.net/qq_40748967/article/details/122467138