Question

I very much want to subclass a Qt QQuickItem class for use in QML, therefore giving it a lot of C++ logic behind the scenes. However, since QML will instantiate it and own it, not the C++ side, I do not know how (if it is possible) to pass pointers or connections between this new object and other C++ objects in the system. Is this possible?

Was it helpful?

Solution

You can register a global QML object in you main.cpp which poins to an arbitrary QObject.

Brain *brain = new Brain();

QQmlApplicationEngine engine;
QQmlContext *context = engine.rootContext();
context->setContextProperty("brain", brain);

Now you have brain available globally in QML. You can pass it to a custom component, for example

VisibleComponent  {
    id: vico1
    width: 300
    height: 300

    Component.onCompleted: {
        vico1.setLogic(brain)
    }
}

This requires a Q_INVOKABLE void setLogic(Brain* brain); in VisibleComponent.

I have a running example project of this code, let me know if you need it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top