问题
I'm wondering How I can have a string in QML that will be occupied with some arguments? Some thing like this in Qt:
QString str("%1 %2");
str = str.arg("Number").arg(12);//str = "Number 12"
回答1:
In QML environment, the arg() function already added to the string prototype, so basically you can use the string.arg() in QML just like C++.
There is less documentation about this, but I'm sure it works in Qt 4.7 + QtQuick 1.1
Take at look at the Qt 5 doc : http://qt-project.org/doc/qt-5.0/qtqml/qml-string.html
回答2:
just use :
"foo%1".arg("bar");
回答3:
Arguments are totally unnecessary in this example. In JS, we have simple string concatenation which also supports numbers in between, so you can achieve this with a simple
var str = 'Number' + ' ' + 12
If you really want arguments in non-literal strings, you can just replace the %1 with the replacement. QString::arg (with one argument) is nothing more than the following:
function stringArg(str, arg)
{
for(var i = 1; i <= 9; ++i)
if(str.indexOf('%'+i) !== -1)
return str.replace('%'+i, arg);
return str;
}
So your code becomes:
var str = "%1 %2"
str = stringArg(str, "Number")
str = stringArg(str, 12)
(Note that this function can only handle %1..%9, while QString::arg can handle up to %99. This requires a bit more logic, since %10 is teated as a %1 in my code. So this is not exactly the same as QString::arg, but it will suffice in the most cases. You could also write a stringArg function taking multiple replacement arguments, but for the simplicity I just wrote this one here.)
回答4:
You might be able to do this with a jQuery plugin:
http://docs.jquery.com/Plugins/Validation/jQuery.format
import "jQuery.js" as JQuery
Page {
property string labelStub: "hello {0}"
Label {
text: JQuery.validator.format(labelStub, "world")
}
}
来源:https://stackoverflow.com/questions/12758282/what-is-the-equivalence-for-qstringarg-in-qml