最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Joining 2 strings in QML - Stack Overflow

programmeradmin0浏览0评论

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:

Share Improve this question edited Sep 28, 2017 at 14:53 asked Sep 28, 2017 at 14:40 user8024280user8024280 1
  • Possible duplicate of What is the equivalence for QString::arg() in QML – user3151675 Commented Sep 28, 2017 at 14:42
Add a ment  | 

2 Answers 2

Reset to default 4

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

You can do this with args

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

评论列表(0)

  1. 暂无评论