10.6. tr() and Internationalization

[ fromfile: linguist.xml id: linguist ]

If you write a program that will ever be translated into another language (internationalization), Qt Linguist and Qt translation tools have already solved the problem of how to organize and where to put the translated strings. To prepare your code for translation, you can use QObject::tr() to surround any translatable string in your application. When used as a non-static function, it takes the object's class name, as provided by QMetaObject, as a "context" for grouping translated strings.

tr() serves two purposes:

  1. It makes it possible for Qt's lupdate tool to extract all the translatable string literals.

  2. If a translation is available, and the language has been selected, the function returns the translated string.

If no translation is available, tr() returns the original string.

[Note]Note

It is important that each translatable string is indeed fully inside the tr() function and extractable at compile time. For strings that have parameters, use the QString::arg() function to place parameters inside translated strings. For Example:

statusBar()->message(tr("%1 of %2 complete. progress: %3%")
                    .arg(processed).arg(total).arg(percent));

This way, translations can place the parameters in a different order in the situations where language changes the order of words/ideas.

The following tools are used for translation:

  1. lupdate – Scans designer .ui files and C++ files for translatable strings. Generates a .ts file.

  2. linguist – Edits .ts files and enables user to enter translations.

  3. lrelease – Reads .ts files and generates .qm files, which are used by the application to load translations.

See the linguist manual for further details on how to use these tools.