QML Internationalization

Strings in QML can be marked for translation using the qsTr(), qsTranslate(), QT_TR_NOOP(), and QT_TRANSLATE_NOOP() functions.

For example:

 Text { text: qsTr("Pictures") }

These functions are standard QtScript functions; for more details see QScriptEngine::installTranslatorFunctions().

QML relies on the core internationalization capabilities provided by Qt. These capabilities are described more fully in:

You can test a translation with the QML Viewer using the -translation option.

Example

First we create a simple QML file with text to be translated. The string that needs to be translated is enclosed in a call to qsTr().

hello.qml:

 import QtQuick 1.0

 Rectangle {
     width: 200; height: 200
     Text { text: qsTr("Hello"); anchors.centerIn: parent }
 }

Next we create a translation source file using lupdate:

 lupdate hello.qml -ts hello.ts

Then we open hello.ts in Linguist, provide a translation and create the release file hello.qm.

Finally, we can test the translation:

 qmlviewer -translation hello.qm hello.qml

You can see a complete example and source code in the QML Internationalization example.

Notes provided by the Qt Community
Informative
  • 5

Votes: 1

Coverage: Qt library 4.7, 4.8

Picture of sigrid sigrid

Lab Rat
20 notes

This person works for Qt Development Frameworks. Nokia Certified Qt Developer

Dynamic translation in QML

The following wiki page [developer.qt.nokia.com] explains how you can do dynamic translation in QML and get around the fact that QDeclarativeEngine does not provide a convenient way to know when the strings should be retranslated.

[Revisions]

Best Practice
  • 5

Votes: 1

Coverage: Qt library 4.7, 4.8

Picture of dourouc05 dourouc05

Ant Farmer
1 note

How to Concatenate Strings?

What is good with Qt is that you can translate quite complex strings, with many concatenations, without having to worry too much about the ordering of the words in other languages.

An example of what is completely wrong:

  1. Text { text: qsTr("My friend number ") + number + qsTr(" is called ") + name }

That can be corrected in:

  1. Text { text: qsTr("My friend number %1 is called %2").arg(number).arg(name) }

Don’t forget the third argument of Qt’s tr:

  1. Text { text: qsTr("There are %1 bottle").arg(number) + (number !== 1 ? "s" : "") + qsTr(" on the wall. ") }

should be replaced by

  1. Text { text: qsTr("There are %n bottle(s) on the wall. ", "", count) }

Your translators will welcome those changes!

See http://qt.nokia.com/doc/qq/qq19-plurals.html and other Qt Quarterly articles on translations.

[Revisions]