Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Java Script function as parameter to C++ function

Tags:

c++

qt

qml

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); });
like image 966
Roman Kolesnikov Avatar asked Apr 05 '15 08:04

Roman Kolesnikov


People also ask

Can we use a function as a parameter of another function in C?

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.

Can you use a function as a parameter of another function JavaScript?

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.

Can you use a function as a parameter of another function?

Functions, like any other object, can be passed as an argument to another function.

How do you pass a function with a parameter?

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.


1 Answers

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)});
like image 144
Meefte Avatar answered Dec 18 '22 14:12

Meefte