将 Java Script 函数作为参数传递给 C++ 函数

2022-01-19 00:00:00 qt qml c++

我在 C++ 中声明我的对象

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

并使其对 qml 可用:

and make it available to qml:

engine()->rootContext()->setContextProperty("action", new Action());

如何将javascript函数作为参数传递给getData()方法并在C++端调用该函数?

How to pass to getData() method javascript function as parameter and call this function on C++ side?

所以从 QML 的角度来看,它应该是这样的:

So from QML point of view it should looks like:

action.getData(function(data) { alert(data); });

推荐答案

可以使用 QJSValue.例如:

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

相关文章