[英]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.