Ever used Q_INVOKABLE ?
OK !! Let's know the use behind this.
If you want to communicate b/w QML file and cpp file, i.e if you like to call a method of cpp file from QML, then we have to take help of Q_INVOKABLE.In-order to let QML file know( discover ) the method in cpp file, we have to declare the method as Q_INVOKABLE.
Practically,In hpp file, declare the method like this.
In cpp file, define this method and make cpp file object available to QML using context property of QMLDocument.
In the last line of above code, I'm referencing cpp class object as "cppObj". So with this name, i can call method's of this object.
Lastly, in QML file make a call for the method.
Don't forget, decalring Q_OJECT in .hpp file.
The complete example is illustrated in this post.
OK !! Let's know the use behind this.
If you want to communicate b/w QML file and cpp file, i.e if you like to call a method of cpp file from QML, then we have to take help of Q_INVOKABLE.In-order to let QML file know( discover ) the method in cpp file, we have to declare the method as Q_INVOKABLE.
Practically,In hpp file, declare the method like this.
Q_INVOKABLE void onButtonClicked();
In cpp file, define this method and make cpp file object available to QML using context property of QMLDocument.
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this); // create root object for the UI pane = qml->createRootObject(); // set created root object as a scene app->setScene(pane); qml->setContextProperty("cppObj", this);
In the last line of above code, I'm referencing cpp class object as "cppObj". So with this name, i can call method's of this object.
Lastly, in QML file make a call for the method.
Button {
text: qsTr("Click me")
verticalAlignment: VerticalAlignment.Center
horizontalAlignment: HorizontalAlignment.Center
onClicked: {
cppObj.onButtonClicked();
}
}
Don't forget, decalring Q_OJECT in .hpp file.
The complete example is illustrated in this post.
No comments:
Post a Comment