Search code examples
c++qtqmlqtquick2qqmlcontext

Can I access, from C++, the QQmlContext in which a QtObject is contained?


I have a sorta-singleton helper object that, however, I don't want to be actually a singleton, because I prefer to put things on the stack/heap. So I created it on the heap and set it as a contextProperty of my root QQmlContext. I also have a QObject subclass in C++, which is instantiated within the QQmlContext's object tree.

Can I access, from C++, the QQmlContext in which the QObject is contained, to get to the contextProperty in question?

I know I can do something like this:

// in main.cpp
engine.rootContext()->setContextProperty("_cp", cp);

// in foo.qml
MyQObjectSubclass {
    cp: _cp
}

// in myqobjectsubclass.h:
// (macro from http://syncor.blogspot.bg/2014/11/qt-auto-property.html)
AUTO_PROPERTY(MyQObjectSubclass*, cp)

But that means I must always clog my MyQObjectSubclass QML instances with the "cp: _cp" boilerplate.


Solution

  • I just found a way:

    QQmlEngine::contextForObject(myQObject)
    

    Haven't tried it yet.

    Equivalently:

    #include <QtQml>
    
    // ...
    
    qmlContext(myQObject);