简体   繁体   English

在QML中加入2个字符串

[英]Joining 2 strings in QML

I set property of qml using C++ function (from library, I do not see implementation), after use of this function property on button is changed as expected (value which I set from c++ code), but on text is set just "My name is:" without value. 我使用C ++函数设置qml的属性(来自库,我没有看到实现),使用此函数属性后按钮按预期更改(我从c ++代码设置的值),但是文本设置只是“我的名字是:“没有价值。 My question is, how to join two strings in QML javascript function when one is result of qsTr() function and second is property set from C++? 我的问题是,当一个是qsTr()函数的结果时,如何在QML javascript函数中连接两个字符串,第二个是从C ++设置的属性

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
}

On Button: John Smith 按钮: John Smith

On Text: My Name is: 在文本上: My Name is:

The problem is not joining strings, it's the binding. 问题不在于加入字符串,而是绑定。

When you are doing myText.text = ... name is not yet set. 当你在做myText.text = ... name还没有设置。 And since you are doing an imperative assignation, it won't be updated if name changes. 由于您正在执行命令式分配,因此如果name更改,则不会更新。

You could maintain a binding with Qt.binding() : 您可以使用Qt.binding()维护绑定:

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

Or alternatively, you could just do it declaratively in myText : 或者,您可以在myText声明方式执行此操作:

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

More information here : http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html 更多信息请访问: http//doc.qt.io/qt-5/qtqml-syntax-propertybinding.html

You can do this with args 你可以用args做到这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 连接2个字符串 - Joining 2 Strings 将 javascript 中的字符串乘以 arrays,最后不加入它们 - Multiply arrays of strings in javascript, not joining them at the end AngularJS数学加入字符串而不是添加 - AngularJS math joining strings instead of adding 通过在JavaScript中加入2个字符串来设置'calc()'值不起作用 - Setting 'calc()' value by joining 2 strings in JavaScript not working 用逗号和空格连接两个字符串 - Joining two strings with a comma and space between them 如何通过连接所有字符串来折叠数组,但保留对象 - How to collapse an array by joining all strings, but leaving objects 联接字符串/变量时,使用+和的区别? - Javascript - Difference between using + and , when joining strings/variables? 从数组中加入字符串并将其呈现在 div 中后如何创建换行符? - How to create linebreaks after joining strings from an array and rendering it inside a div? 在连接使用String.fromCharCode创建的字符串时,Array.join插入额外的字符 - Array.join inserts extra characters when joining strings created with String.fromCharCode 高效地将字符串的大型嵌套数组(即树)“连接”为单个字符串 - Efficiently “joining” a large nested array (i.e. tree) of strings into a single string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM