将 Javascript 回调传递给 Qml 中的 C++ 调用方法

2022-01-19 00:00:00 qt qtquick2 qml javascript

在 C++ 中,我有一个带有可调用函数的类,我想做的是从 QML/Javascript 调用该方法(我已经开始工作了)并将其传递给 Javascript 回调.

In C++ I have a class with an invokable function, what I would like to do is call that method from QML/Javascript (this I've gotten to work) and pass it a Javascript callback.

在代码中,我将我的类定义为:

In code, I define my class like:

class MyObject: public QObject
{

Q_OBJECT

public:
    Q_INVOKABLE void doSomething(quint64 x, /* what goes here? */ jsCallback)
    {
        x += 1;

        // I suspect this will require a invocation mechanism but 
        // this shows what I'd like to do
        jsCallback(x);
    }
};

在我的 QML 中,我想做类似的事情:

And in my QML, I would like to do something like:

Rectangle {

    function myCallback(x){
        console.log("x=" + x);
    }

    MouseArea{
        anchors.fill: parent
        onClicked:{
            myObject.doSomething(2, myCallback);
        }
    }
}

所以当我点击 Rectangle 时,我会在控制台中看到 x=3.我将如何在 C++ 中定义参数并调用回调以完成此操作?

So that when I click on the Rectangle, I would see x=3 in the console. How would I define the parameter in C++ and invoke the callback in order to accomplish this?

谢谢!

推荐答案

我想我已经想通了.我最终做的是在我的 C++ 类中实现它,如下所示:

I think I've figured this out. What I ended up doing was implementing this in my C++ class like such:

class MyObject: public QObject
{

Q_OBJECT

public:
    Q_INVOKABLE void doSomething(quint64 x, QJSValue jsCallback)
    {
        x += 1;

        QJSValue val = jsCallback.engine()->newObject();
        val.setProperty("x", x);

        jsCallback.call(QJSValueList { val });
    }
};

然后我可以访问回调中的值,例如:

And then I can access the value in my callback like:

function myCallback(x){
    console.log("x=" + x.x);
}

相关文章