【问题标题】:Joining 2 strings in QML在 QML 中加入 2 个字符串
【发布时间】:2017-09-28 14:40:08
【问题描述】:

我使用 C++ 函数设置了 qml 的属性(来自库,我没有看到实现),在使用这个函数属性之后 on 按钮按预期更改(我从 c++ 代码设置的值),但在文本上设置的只是“我的名字是:”没有值。我的问题是,如何连接两个字符串 在 QML javascript 函数中,一个是 qsTr() 函数的结果,第二个是从 C++ 设置的 property

property string name: ""

function myFunction() {
   myText.text = qsTr("My Name is: ") + name;
   //myText.text = qsTr("My Name is: " + name);//another try
}
Text{
    id: myText
    text: ""
}
Button {
    text: name
}

打开按钮:John Smith

文字:My Name is:

【问题讨论】:

标签: javascript c++ qt qml qt-quick


【解决方案1】:

问题不是加入字符串,而是绑定。

当你在做 myText.text = ... name 时还没有设置。而且由于您正在执行命令式分配,因此如果 name 更改,它将不会更新。

您可以与Qt.binding() 保持绑定:

myText.text = Qt.binding(function() {return qsTr("My Name is: ") + name;});

或者,您也可以在 myText 中以声明方式进行:

Text {
    id: myText
    text: qsTr("My Name is: ") + name
}

更多信息在这里:http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html

【讨论】:

    【解决方案2】:

    你可以用 args 做到这一点

    var message = "My name is %1";
    var name = "John Smith";
    myText.text = message.arg(name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2019-01-02
      • 2020-04-01
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      相关资源
      最近更新 更多