QML to CPP
Good Day!
How to pass a value or string from QML to CPP.
It is like, when i clicked the MouseArea from QML it will send a number/string to cpp. And cpp will do some calculation.
Please Help.
12 replies
Good Day!How to pass a value or string from QML to CPP.
It is like, when i clicked the MouseArea from QML it will send a number/string to cpp. And cpp will do some calculation.Please Help.
Please post it in a single section and avoid [developer.qt.nokia.com] multiple posts.
Did you try the relevant documentation [developer.qt.nokia.com] ?
Good Day!How to pass a value or string from QML to CPP.
It is like, when i clicked the MouseArea from QML it will send a number/string to cpp. And cpp will do some calculation.Please Help.
Please post it in a single section and avoid [developer.qt.nokia.com] multiple posts.
this “avoid” path does not exist.
The link Andre posted has all the required information and has sample code also :).
Basically you create a QObject derived class with a QML callable function ( By placing Q_INVOKABLE before it), and then create an instance of that class inside your c++ code and make the created object available in qml by exporting it with QDeclarativeContext::setContextProperty, and call qml invokable function from QML side when you want to pass data
Example :
C++ Code
- QmlApplicationViewer viewer;
- YourQmlObject qmlobject(&viewer);
- QDeclarativeContext * context = viewer.rootContext();
- context->setContextProperty("qmlobject",&basicCalc);
qml side
- qmlobject.callFunction("stringyouwanttopass");
callFunction is declared and defined in your YourQmlObject class and YourQmlObject is a QObject derived class.
Declaration of callFunction is
Ok.. I would suggest you to visit page
http://developer.qt.nokia.com/wiki/Introduction_to_Qt_Quick_for_Cpp_developers
and then search for “Calling C++ methods from QML”, you will get the answer you are looking for :)
- // MyItem.qml
- import QtQuick 1.0
- Item {
- width: 100; height: 100
- MouseArea {
- anchors.fill: parent
- onClicked: {
- myObject.cppMethod("Hello from QML")
- myObject.cppSlot(12345)
- }
- }
- // CPP code
- {
- Q_OBJECT
- public:
- qDebug() << "Called the C++ method with" << msg;
- }
- public slots:
- void cppSlot(int number) {
- qDebug() << "Called the C++ slot with" << number;
- }
- };
- int main(int argc, char *argv[]) {
- QDeclarativeView view;
- MyClass myClass;
- view.rootContext()->setContextProperty("myObject", &myClass;);
- view.show();
- return app.exec()
- }
You must log in to post a reply. Not a member yet? Register here!





