Pass Java Script function as parameter to C++ function

僤鯓⒐⒋嵵緔 提交于 2019-12-20 19:43:29

问题


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); });

回答1:


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)});


来源:https://stackoverflow.com/questions/29455675/pass-java-script-function-as-parameter-to-c-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!