I declare my object in C++
class Action : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name)
public:
Action(): QObject(0) {}
QString name() const { return "rem"; }
Q_INVOKABLE void getData() {};
}
and make it available to qml:
engine()->rootContext()->setContextProperty("action", new Action());
How to pass to getData() method javascript function as parameter and call this function on C++ side?
So from QML point of view it should looks like:
action.getData(function(data) { alert(data); });
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.
In JavaScript, passing a function as a parameter to another function is similar to passing values. The way to pass a function is to remove the parenthesis () of the function when you assign it as a parameter.
Functions, like any other object, can be passed as an argument to another function.
Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.
It is possible using QJSValue. For example:
//C++
Q_INVOKABLE void getData(QJSValue value) {
if (value.isCallable()) {
QJSValueList args;
args << QJSValue("Hello, world!");
value.call(args);
}
}
//QML
action.getData(function (data){console.log(data)});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With