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. 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++?
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
On Text: My Name is:
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. 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++?
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
On Text: My Name is:
- Possible duplicate of What is the equivalence for QString::arg() in QML – user3151675 Commented Sep 28, 2017 at 14:42
2 Answers
Reset to default 4The problem is not joining strings, it's the binding.
When you are doing myText.text = ...
name
is not yet set. And since you are doing an imperative assignation, it won't be updated if name
changes.
You could maintain a binding with Qt.binding()
:
myText.text = Qt.binding(function() {return qsTr("My Name is: ") + name;});
Or alternatively, you could just do it declaratively in myText
:
Text {
id: myText
text: qsTr("My Name is: ") + name
}
More information here : http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html
You can do this with args
var message = "My name is %1";
var name = "John Smith";
myText.text = message.arg(name);