将Javascript回调传递给Qml中的C ++ Invoked方法 [英] Passing a Javascript callback to a C++ Invoked method in Qml
问题描述
在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);
}
这篇关于将Javascript回调传递给Qml中的C ++ Invoked方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!