Dynamic text using QString::arg() in QML
The following web page mentions how to achieve dynamic text using QString::arg() :
http://doc.qt.nokia.com/4.7/internationalization.html#use-qstring-arg-for-dynamic-text
This looks wonderful for localized text where the arguments are not always at the same position:
- label.setText(tr("%1 of %2 files copied.\nCopying: %3")
- .arg(done)
- .arg(total)
- .arg(currentFile));
How to achieve the same thing in QML ?
Is there a QML interface for QString::arg ?
Do I need to create one ?
I wrote this little qml file that does the job in ECMAScript but I am not really happy with it:
- import Qt 4.7
- Rectangle {
- width: 100
- height: 62
- function stringFormat(str, args) {
- for(var i=0; i<args.length; i++)
- str = str.replace(eval("/%"+(i+1)+"/"), args[i]);
- return str;
- }
- Component.onCompleted: {
- var str = stringFormat(qsTr("%1 of %2 files copied.-Copying: %3"), new Array("5", "10", "file.txt"));
- console.log("str="+str);
- }
- }
7 replies
Indeed, we need to move further away from fixing strings in this way, not moving back towards it. There are many problems with fixing strings, that multiply with localization. One issue is that not all languages would have all arguments in the same place, and another one is that plural froms may work very differently across languages. There may even be more than one plural form, such as in some Eastern European languages.
As for a temporary workaround, you could subclass QObject and provide some invokable helper functions that take care of formatting the strings, and use setContextProperty on the QML view to “inject” your string formatting helper. This would also make your QML code easier to read, as you don’t do the formatting in there, and the details of how the string is formatted are hidden.
Imaginary example call:
- text: formatter.copyProgress(done, total, currentFile)
Yes.
The JavaScript environment in QML is slightly modified from the ECMAScript standard. If you take a look at the implementation of the QScriptEngine::installTranslatorFunctions(const QScriptValue &object) function in Qt4, you’ll note that we actually modify the String prototype to include the .arg() function. In Qt5 we do a similar modification, in QV8Engine.cpp, where we add the arg function to the String prototype (which calls through to a qml builtin function called stringArg).
That is, all JavaScript String objects in QML have a non-standard arg() function, which behaves similarly to the QString::arg() function we’re all familiar with from C++.
The JavaScript environment also has several other modifications, including adding the qsTr and similar functions to the global object.
Cheers,
Chris.
You must log in to post a reply. Not a member yet? Register here!



