2017-09-28 53 views
1

我使用C++函數(來自庫,我沒有看到實現)設置qml屬性,在按鈕上使用此函數屬性 後按預期更改(我從C++代碼設置的值),但在文本上設置「我的名字是:」沒有價值。我的問題是,如何在QML javascript函數中加入兩個字符串 當其中一個是的結果qsTr()函數和第二個是屬性設置從C++嗎?在QML中加入2個字符串

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 
} 

開按鈕:John Smith

在文字:My Name is:

+0

可能的複製[ QML中QString :: arg()的等價性是什麼(https://stackoverflow.com/questions/12758282/what-is-the-equivalence-for-qstring) ARG-在-QML) – the4kman

回答

0

您可以ARGS

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

的問題是不加入琴絃做到這一點,它的約束力。

當你在做myText.text = ...name尚未設置。而且,由於您正在進行必要的分配,因此如果name發生更改,它將不會更新。

你可以保持與Qt.binding()綁定:

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

或者,你可以只是做聲明中myText

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

更多信息此處的http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html