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.


  • Moderators

    Hi @zeroc8 Thats because the Window you are trying to find is itself a root object and not a child. Thus findChild wont work. Use rootObjects() 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.


  • Moderators

    @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.background

        MsgCtrol {
            id: ctrl
            objectName: "msgctrl"
            onPlayMsg: Mainjs.playMsg(message);
        }

  • Moderators

    @p3c0 Ok this looks good. Now what is rootObject ? QQmlApplicationEngine doesnot have rootObject it has rootObjects( note 's' ). Are you sure you are using QQmlApplicationEngine ?



  • 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.


  • Moderators

    @zeroc8 Does it work if you have Item instead of Window as root element ?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.