Cannot get pointer to qml object instance:
-
I'm trying to access an object instance that is created in QML
main.qml:
Window { id: mainwindow objectName: "MainWindow" width: 1280; height: 720 }
main.cpp:
QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml")));; QObject* mainWindow = engine.rootContext()->findChild<QObject*>("MainWindow"); if(!mainWindow) throw("cannot find MainWindow");
The returned mainWindow is null, why is that? Any ideas? Thanks.
-
Hi @zeroc8 Thats because the
Window
you are trying to find is itself a root object and not a child. ThusfindChild
wont work. UserootObjects()
to get the root objects and then get the first item from the list. So the following gives pointer to first window:QObject* mainWindow = engine.rootObjects().first();
-
@p3c0
thanks, works with an instance of a builtin textcontrol. Hoever, when I try this with my own control, I cannot get a hold of it.qmlRegisterType<MsgCtrol>("MyStuff",1,0,"MsgCtrol");
QObject* msgCtrl = rootObject->findChild<QObject*>("msgctrl");
if(!msgCtrl) throw("cannot find msgctrl");MsgCtrol {
objectName: "msgctrl"
}Any idea what's going on here? Thanks.
-
@zeroc8 And where is this
MsgCtrol
instantiated in ? Can you post the code ? -
MsgCtrol is instantiated in my main.qml file:
Window {
id: mainwindow
width: 1280; height: 720
color: ctrl.backgroundMsgCtrol { id: ctrl objectName: "msgctrl" onPlayMsg: Mainjs.playMsg(message); }
-
@p3c0 Ok this looks good. Now what is
rootObject
?QQmlApplicationEngine
doesnot haverootObject
it hasrootObjects
( note 's' ). Are you sure you are usingQQmlApplicationEngine
? -
qmlRegisterType<MsgCtrol>("MyStuff",1,0,"MsgCtrol");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));;The MsgCtrol gets instanced fine, but I need to hook it up to some additional webhandler, that's whey I wantend to get a hold of the instance from the outside.
The solution that works is to make the webhandler a member of MsgCtrol and hook up the connections there, but that doesn't seem right. -
@zeroc8 Does it work if you have
Item
instead ofWindow
as root element ?