How to access a root context from QObject?



  • Hi everybody!

    I've created my QObject-derived subclass and registered it with the QML type system. Now I need to access the root context from my object's method. How can I do it?

    Thank you!



  • See the qmlContext() and qmlEngine() documentation. You may need to look at the qqmlengine.cpp source code directly to see that documentation, as qdoc is a broken mess.

    Cheers,
    Chris.



  • Here's the full answer to the question. Inside your QObject derived subclass, you can do the following:

    @
    // get rootContext() and required contextProperty as QVariant
    QVariant myobject_v = qmlEngine(this)->rootContext()->contextProperty("myname");
    // cast QVariant first to QObject* and then to my desired ObjectClass*
    ObjectClass myobject = qobject_cast<ObjectClass>(qvariant_cast<QObject*>(myobject_v));
    @

    http://stackoverflow.com/a/3918893/532513 showed how to cast from QVariant to ObjectClass*, the rest was found through snippets of documentation scattered all over the place. :|


Log in to reply
 

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