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

Passing a Javascript callback to a C++ Invoked method in Qml(将 Javascript 回调传递给 Qml 中的 C++ 调用方法)
本文介绍了将 Javascript 回调传递给 Qml 中的 C++ 调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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++ 调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)