Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Contributor
Posts: 20
Registered: ‎09-12-2012
My Device: Developer
My Carrier: Docomo

how to call a cpp method in qml

how to call a cpp method in qml

i know that we have to create a method with Q_INVOKABLE in cpp  like this 

 

Q_INVOKABLE void calculateValue();

 

and iam calling this method in qml like this 

Page {
attachedObjects: [
Calculate {
id: cal
}]

Button {
id: calculate
text: "Calculate"
onClicked: {
console.log("Button Cicked: " + id)
cal.calculateValue()
console.log("Method Calling Completed\n\ns: ")
}
}

}

 

then it gives an error like this 

 

 

errors: (file:///accounts/1000/appdata/com.example.Sample.testDev_mple_Samplee597aedb/app/native/assets/main.qml:7:9: Calculate is not a type
Calculate {
^)
QmlDocument:createRootNode document is not loaded or has errors, can't create root

 

 

then what is my mistake

Developer
Posts: 217
Registered: ‎09-18-2009
My Device: Z10
My Carrier: O2

Re: how to call a cpp method in qml

Have a look at the HelloWorldDataModel example in github https://github.com/blackberry/Cascades-Samples/tree/master/HelloWorldDataModel

 

You have to register your Calculate class with the qmlRegisterType() method

qmlRegisterType<

HelloWorldDataModel>("custom.lib", 1, 0, "HelloWorldDataModel");

 

Then you have to import it in qml

import

custom.lib 1.0

Developer
Posts: 181
Registered: ‎07-19-2012
My Device: Q5, Q10, Z10, Z30, PlayBook
My Carrier: Carrier

Re: how to call a cpp method in qml

What I am doing is exposing "app" variable to QML which points to instance of my App() class by adding this line in app.cpp:

qml->setContextProperty("app", this);

Then in app.cpp create Q_INVOKABLE method which calls any other c++ class referenced from app.cpp

 

And then in any QML file I can simply do this:

app.myMethod();

 Seems to work just fine. Hope this helps.

---
If you find my post helpful please "like" it and "accept as a solution"