QML to CPP
-
Did you try the "relevant documentation":http://developer.qt.nokia.com/doc/qt-4.7/qml-extending.html ?
-
[quote author="QtK" date="1309431176"]
[quote author="eirnanG" date="1309430672"]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.[/quote]
Please post it in a single section and "avoid":http://developer.qt.nokia.com/forums/viewthread/7325 multiple posts.
[/quote]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
@Q_INVOKABLE void callFunction(QString str);@
-
Ok.. I would suggest you to visit page
http://developer.qt.nokia.com/wiki/Introduction_to_Qt_Quick_for_Cpp_developersand then search for "Calling C++ methods from QML", you will get the answer you are looking for :)
-
You can copy/paste the code here... others can also have a look and advise you something :) or
you can send the code to my mail id by selecting "Send mail" link in my profile page.
-
@
// MyItem.qml
import QtQuick 1.0Item {
width: 100; height: 100MouseArea { anchors.fill: parent onClicked: { myObject.cppMethod("Hello from QML") myObject.cppSlot(12345) } }
@
@
// CPP code
class MyClass : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE void cppMethod(const QString &msg;) {
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[]) {
QApplication app(argc, argv);QDeclarativeView view; MyClass myClass; view.rootContext()->setContextProperty("myObject", &myClass;); view.setSource(QUrl::fromLocalFile("MyItem.qml")); view.show(); return app.exec()
}
@ -
@all thanks to your response..
@changsheng230 thanks! ill try it :)