Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
How to access a root context from QObject?
Alexey last edited by
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?
chrisadams last edited by
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.
cpbotha last edited by
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. :|