Call a qml function from C++.
-
I normally use this line of code to invoke a qml function from c++ and all works well.
@QMetaObject::invokeMethod((QObject*)(this->rootObjects().first()), "CallOk");@
But my situation in a bit different. From the main qml file, by clicking on a button, I load a second qml file.
How can I call its functions from c++?
This line of code does not work.
#QMetaObject::invokeMethod((QObject*)(this->rootObjects().first()), "CallOk");#
I have tried
@this->rootObjects().first()->findChild<QObject*>("aaa");@
using the name of the object but does not work.
Can you suggest me the right way? -
Use slots or Q_INVOKABLE.
c++
@class Blah {
....
public slots:
void iveBeenClicked()
};@Pass class to qml
@
Blah foo;
view->rootContext()->setContextProperty("myblah", &blah);
@Qml
@
Button {
onClicked: myblah.iveBeenClicked()
}Button {
id: lateButton
}Component.onCompleted: lateButton.clicked.connect(myblah.iveBeenClicked())
@ -
Sorry but it isn't my situation.
I need to call a qml function from c++.
This line of code
@QMetaObject::invokeMethod((QObject*)(this->rootObjects().first()), "CallOk");@
works only with a function in the main qml file.
If you load a second qml file, the functions in it are not accesible from C++. -
You just make a C++ object that emits a signal the normal way, then make use of "Connections":http://qt-project.org/doc/qt-5/qml-qtqml-connections.html in QML. You need to have the "class available to QML":http://qt-project.org/doc/qt-5/qtqml-cppintegration-contextproperties.html.
So if you have a signal runFunction in your C++ class you can then just connect to it in your QML file like this:
@
Connections {
target: myCppClass
onRunFunction: myQMLFuntion();
}
@Hope it helps!
-
[quote author="mrdebug" date="1405861088"]
I normally use this line of code to invoke a qml function from c++ and all works well.
@QMetaObject::invokeMethod((QObject*)(this->rootObjects().first()), "CallOk");@
But my situation in a bit different. From the main qml file, by clicking on a button, I load a second qml file.
How can I call its functions from c++?
This line of code does not work.
#QMetaObject::invokeMethod((QObject*)(this->rootObjects().first()), "CallOk");#
I have tried
@this->rootObjects().first()->findChild<QObject*>("aaa");@
using the name of the object but does not work.
Can you suggest me the right way?[/quote]Try this,
@
QMetaObject::invokeMethod((QObject*)(engine.rootObjects().at(0)->findChild<QQuickItem*>("myObject")), "callMyMethod");
@Provided you have given an objectName to the Item (here myObject)