Question

Let there be a C++ class which contains signals and some functions accessible from QML. Now, in order to access the members of that class in QML, I write something like:

myClass
{
   id: abc

   x: 100    
   onXChanged: {console.log ("xx");}
}

Assuming x is a member of the actual C++ class, the above code does work.


Now, I have an object of the C++ class i.e. myClass created in a relevant C++ file.

Question:
Instead of creating a new object of the same class in QML, is it possible and sensible to access and use the already created C++ object in QML?

Was it helpful?

Solution

You can use context properties for this. You would be writing something like this:

...

MyClass myClassObject;
QQuickView view;
view.rootContext()->setContextProperty("myClassContextProperty", &myClassObject);
view->setSource(QUrl::fromLocalFile("main.qml"));
view->show();

...

and then you could access it in qml as follows:

Button {
    onClicked: myClassContextProperty.x = 100
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top