Calling anonymous QML functions from C++
-
Hi,
I found out, that you can call QML functions from C++ using
@
QMetaObject::invokeMethod(object, "myQmlFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, msg));
@
But that does not work with anonymous QML functions that are passed as an argument to a C++ function, because it has no name.
There is an idea as a workaround "found in a mailing list":http://comments.gmane.org/gmane.comp.lib.qt.qml/1820 that uses signals to make this work.
I think this is somewhat cumbersome and I'd like to make the QML developer be able to use "the natural way".Is there any possibility to solve this issue without signals?
Cheers,
Manuel
EDIT: spelling
-
Hi,
As of Qt 5.0, it is possible to solve this with "QJSValue":http://qt-project.org/doc/qt-5.1/qtqml/qjsvalue.html .
C++ :
@class Foo : public QObject
{
Q_OBJECTpublic : Q_INVOKABLE void bar(QJSValue function) { function.call(QJSValueList() << 42); }
};@
QML :
@Foo.bar(function(result) {
console.log('returned ', result, ' from c++')
})@will output 'returned 42 from c++'
You can also do all sorts of checks on the object passed to the c++ function. In this case, you might want to call "isCallable" to make sure the object is a function.
Cheers
-
Thank you for your answer.
What if I want to call this function asynchronously?
I tried to call this function asynchronously in C++, but it failed.
Cheers