8

我想抓取我的 QML 应用程序的屏幕。但是我的根 QML 对象是ApplicationWindow,所以我不能QQuickView用来显示它。相反,我必须使用QQmlApplicationEngine. 我知道如何使用QQuickView( QQuickWindow::grabWindow) 截屏,但不知道如何使用QQmlApplicationEngine.

我的main文件:

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
    } 

    //...
}
4

3 回答 3

6

您可以使用rootObjects()并将其结果转换为QQuickWindow

foreach(QObject* obj, engine.rootObjects()) {
  QQuickWindow* window = qobject_cast<QQuickWindow*>(obj);
  if (window) {
    QImage image = window->grabWindow();
    qDebug() << image;
  }
}
于 2014-02-11T12:05:53.287 回答
1

您也可以使用QObject *obj、QEvent *ev来截取屏幕截图。

主文件

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

类对象.h

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

类对象.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);
}

每当发生某些事件时,这将截取屏幕截图。

于 2019-11-26T09:15:21.223 回答
0

您可以将 ApplicationWindow(QML) 转换为 QQuickWindow(C++)。然后,很容易截取屏幕截图。

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");
    }
于 2016-07-21T10:38:13.627 回答