1

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:

wair92
  • 446
  • 11
  • 24
  • Possible duplicate of [What is the equivalence for QString::arg() in QML](https://stackoverflow.com/questions/12758282/what-is-the-equivalence-for-qstringarg-in-qml) – Tamás Sengel Sep 28 '17 at 14:42

2 Answers2

3

The 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

GrecKo
  • 6,615
  • 19
  • 23
1

You can do this with args

var message = "My name is %1";
var name = "John Smith";
myText.text = message.arg(name);
Timmetje
  • 7,641
  • 18
  • 36