0
我想獲得qml窗口的winId。我有以下文件。QML獲取加載的qml窗口的winId
main.qml:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
id: myMainWindow
title: "MyMainWindow"
width: 200
height: 200;
visible: true
Component.onCompleted: {
x = 40
y = 40
}
}
和我的main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QWindow>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<FbItem>("fbitem", 1, 0, "FbItem");
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject* m_rootObject = engine.rootObjects().first();
auto rect_area = m_rootObject->findChild<QWindow*>("myMainWindow"); //the id of the Window in qml
//both lines make the application crash
//HWND hWnd = reinterpret_cast<HWND>(rect_area->winId());
WId wid = rect_area->winId();
return app.exec();
}
崩潰的消息是:
The inferior stopped because it triggered an exception.
Stopped in thread 0 by: Exception at 0x13500da, code: 0x0000005: read access violation at: 0x0, flags=0x0 (first chance).
有什麼不對?我怎樣才能獲得我窗戶的勝利?
編輯:我們可以看到rect_area仍然不好。在編輯main.qml:
Window {
id: _component
objectName: "myMainWindow"
...
}
您應該檢查'findChild'返回的值。你的情況可能是null,因爲沒有名爲myMainWindow的窗口。您必須將'objectName:「myMainWindow」'添加到窗口才能訪問它。 – folibis