【问题标题】:How to "pull" data from c++ to qml?如何将数据从 c++“拉”到 qml?
【发布时间】:2019-03-26 14:29:11
【问题描述】:

我想从 qml 中的 c++ 中“拉”数据,如下所示:

   Component.onCompleted: {
        MySettings.loadMainWindowPosition(aAppWnd.x, aAppWnd.y, aAppWnd.width, aAppWnd.height, aAppWnd.visibility);
    }

当 MySettings 以下列方式注册时:

context->setContextProperty("MySettings", m_settings);

但是当我像这样制作函数签名时:

void MySettings::loadMainWindowPosition(int& x, int& y, int& width, int& height, int& visibility)

我收到以下错误:

qrc:/GUI/App.qml:35: 错误:未知方法参数类型:int&

那么如何正确地从 c++ 中“拉”到 qml 中的数据?

更新

我解释得更好。现在我可以从 qml 调用 c++ 函数(并发送参数):

   Component.onCompleted: {
        MySettings.someFunc(111, 222);
    }

在 c++ 代码中,我收到参数值为“111”和“222”的函数调用。

但我想在 c++ 中更改此参数。我想要那样的东西:

   Component.onCompleted: {
        var a;
        var b;
        MySettings.someFunc(a, b);
    }

我想在 c++ 代码中将参数设置为“333”和“555”。所以在调用 MySettings.someFunc(a, b) 之后,我期望 (a==333) 和 (b==555)。

如何做到这一点?

【问题讨论】:

  • 不能传引用,js不支持这种类型。请参阅here 了解更多信息。而是传递一个带有属性的对象,然后在 QML 中更新它。
  • @folibis 你能提供一些例子吗?我阅读了您的链接,但没有得到如何调用从 qml 中返回参数值的 c++ 函数:(

标签: c++ qt qml qt5 qqmlcomponent


【解决方案1】:

当从 QML 调用 C++ 函数时,不要尝试将返回值作为参考参数。相反,使用返回值。要在一次调用中传输多个值,请定义您的 C++ 方法,如

Q_INVOKABLE QVariantList someFunc() { ... }

并通过在 QML 中使用它

Component.onCompleted: {
    var returnValues = MySettings.someFunc();
    //access the returnValues via list indices here:
    var a = returnValues[0];
    var b = returnValues[1];
}

【讨论】:

    【解决方案2】:

    通过引用传递值不能从 QML 调用 c++ 函数。如果您想要同步调用,请在您的 c ++ 代码中使用链接:

    QVariantList MySettings::someFunc(int a, int b){
    
            QVariantList list;
            list.append(a + 5); // edit the passed values here
            list.append(b + 5); // edit the passed values here
            return list;
        }
    

    在你的 QML 代码中有类似的东西:

    var test = gapi.someFunc(3,2); // pass values here and get the new ones
    console.log("The return data" + test);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多