将参数从 C++ 传递到 QML [英] Passing parameters from C++ to QML

查看:68
本文介绍了将参数从 C++ 传递到 QML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些参数从 C++ 传递给 QML,以便 QML 可以用它们做一些事情.

I want to pass some parameters from C++ to QML, so that QML can do something with them.

有点像这样:

void MyClass::myCplusplusFunction(int i, int j)
{
    emit mySignal(i, j);
}

在 QML 中,每次发出 mySignal(i, j) 时,我想调用一个 QML 函数并使用 ij.

In QML, every time that mySignal(i, j) is emitted, I want to call a QML function and do stuff with i and j.

Connections {
    target: myClass
    // mySignal(i, j) is emitted, call myQmlFunction(i,j)
}

我该怎么做?

推荐答案

假设你在 cpp 端有一个信号:

Let's say you have a signal in cpp side:

void yourSignal(int i, QString t)

您有两个选择:

  • 将您的类注册为 qml 类型并将其用作 qml 对象.该对象将从 QML 端初始化.参考:

qmlRegisterType("com.mycompany.qmlName", 1, 0, "ClassNameQml");

然后,在 qml 中:

Then, in qml:

import QtQuick 2.9
import com.mycompany.qmlName 1.0

Item{
    ClassNameQml{
        id: myQmlClass
        onYourSignal: {
            console.log(i,t); // Do whatever in qml side
        }
    }
}

  • 将您的类添加为 qml 变量.当您需要多次重复使用您的对象时,此选项是首选.参考:

    view.rootContext()->setContextProperty("varName", &cppObject);

    然后,在 qml 中:

    Then, in qml:

    import QtQuick 2.9
    Item{
        Connections{
            target: varName
            // In QML for each signal you have a handler in the form "onSignalName"
            onYourSignal:{
                // the arguments passed are implicitly available, named as defined in the signal
                // If you don't know the names, you can access them with "arguments[index]"
                console.log(i,t); // Do whatever in qml side
            }
        }
    }
    

    这篇关于将参数从 C++ 传递到 QML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆