我想获取一个 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).
有什么问题吗?我怎样才能获得我的窗口的winId?
编辑:我们可以看到 rect_area 仍然有问题。在编辑后的 main.qml 文件中:
Window {
id: _component
objectName: "myMainWindow"
...
}
findChild
返回的值。在你的情况下,它可能是null,因为没有名为“myMainWindow”的窗口。你必须将objectName: "myMainWindow"
添加到窗口中才能访问它。 - folibis