2

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?

0

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.