我想抓住我的QML应用程序的屏幕。但我的根QML对象是ApplicationWindow
,因此我无法使用QQuickView
来显示它。相反,我必须使用QQmlApplicationEngine
。
我知道如何使用QQuickView
(QQuickWindow::grabWindow
)截取屏幕截图,但不知道如何使用QQmlApplicationEngine
。{/ p>
我的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
}
//...
}
答案 0 :(得分:5)
您可以使用rootObjects()
并将其结果投射到QQuickWindow
:
foreach(QObject* obj, engine.rootObjects()) {
QQuickWindow* window = qobject_cast<QQuickWindow*>(obj);
if (window) {
QImage image = window->grabWindow();
qDebug() << image;
}
}
答案 1 :(得分: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");
}
答案 2 :(得分:0)
您也可以使用 QObject * obj,QEvent * ev 截屏。
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);
}
每当发生某些事件时,这都会截取屏幕截图。