Writing Source Code for Translation

Writing cross-platform international software with Qt is a gentle, incremental process. Your software can become internationalized in the stages described in the following sections. For more information about internalizing Qt Quick application, see Internationalization and Localization with Qt Quick.

Using QString for All User-Visible Text

Since QString uses the Unicode encoding internally, every language in the world can be processed transparently using familiar text processing operations. Also, since all Qt functions that present text to the user take a QString as a parameter, there is no char * to QString conversion overhead.

Strings that are in "programmer space" (such as QObject names and file format texts) need not use QString; the traditional char * or the QByteArray class will suffice.

You're unlikely to notice that you are using Unicode; QString, and QChar are just easier versions of the crude const char * and char from traditional C.

char * strings in source code are assumed to be UTF-8 encoded when being implicitly converted to a QString. If your C string literal uses a different encoding, use QString::fromLatin1() or QTextCodec to convert the literal to a Unicode encoded QString.

Using tr() for All Literal Text

Wherever your program uses a string literal (quoted text) that will be presented to the user, ensure that it is processed by the QCoreApplication::translate() function. Essentially all that is necessary to achieve this is to use the tr() function to obtain translated text for your classes, typically for display purposes. This function is also used to indicate which text strings in an application are translatable.

For example, assuming the LoginWidget is a subclass of QWidget:

 LoginWidget::LoginWidget()
 {
     QLabel *label = new QLabel(tr("Password:"));
     ...
 }

This accounts for 99% of the user-visible strings you're likely to write.

If the quoted text is not in a member function of a QObject subclass, use either the tr() function of an appropriate class, or the QCoreApplication::translate() function directly:

 void some_global_function(LoginWidget *logwid)
 {
     QLabel *label = new QLabel(
                 LoginWidget::tr("Password:"), logwid);
 }

 void same_global_function(LoginWidget *logwid)
 {
     QLabel *label = new QLabel(
                 QCoreApplication::translate("LoginWidget", "Password:"), logwid);
 }

Qt indexes each translatable string by the translation context it is associated with; this is generally the name of the QObject subclass it is used in.

Translation contexts are defined for new QObject-based classes by the use of the Q_OBJECT macro in each new class definition.

When tr() is called, it looks up the translatable string using a QTranslator object. For translation to work, one or more of these must have been installed on the application object in the way described in Enabling Translation.

Translating strings in QML works exactly the same way as in C++, with the only difference being that you need to call qsTr() instead of tr(). See also the page on Internationalization and Localization with Qt Quick.

Defining a Translation Context

The translation context for QObject and each QObject subclass is the class name itself. Developers subclassing QObject must use the Q_OBJECT macro in their class definition to override the translation context. This macro sets the context to the name of the subclass.

For example, the following class definition includes the Q_OBJECT macro, implementing a new tr() that uses the MainWindow context:

 class MainWindow : public QMainWindow
 {
     Q_OBJECT

 public:
     MainWindow();
     ...

If Q_OBJECT is not used in a class definition, the context will be inherited from the base class. For example, since all QObject-based classes in Qt provide a context, a new QWidget subclass defined without a Q_OBJECT macro will use the QWidget context if its tr() function is invoked.

Using tr() to Obtain a Translation

The following example shows how a translation is obtained for the class shown in the previous section:

 void MainWindow::createMenus()
 {
     fileMenu = menuBar()->addMenu(tr("&File"));
     ...

Here, the translation context is MainWindow because it is the MainWindow::tr() function that is invoked. The text returned by the tr() function is a translation of "&File" obtained from the MainWindow context.

When Qt's translation tool, lupdate, is used to process a set of source files, the text wrapped in tr() calls is stored in a section of the translation file that corresponds to its translation context.

In some situations, it is useful to give a translation context explicitly by fully qualifying the call to tr(); for example:

 QString text = QScrollBar::tr("Page up");

This call obtains the translated text for "Page up" from the QScrollBar context. Developers can also use the QCoreApplication::translate() function to obtain a translation for a particular translation context.

Using tr() to Localize Numbers

You can localize numbers by using appropriate tr() strings:

 void Clock::setTime(const QTime &time)
 {
     if (tr("AMPM") == "AMPM") {
         // 12-hour clock
     } else {
         // 24-hour clock
     }
 }

In the example, for the US we would leave the translation of "AMPM" as it is and thereby use the 12-hour clock branch; but in Europe we would translate it as something else to make the code use the 24-hour clock branch.

Translating Non-Qt Classes

It is sometimes necessary to provide internationalization support for strings used in classes that do not inherit QObject or use the Q_OBJECT macro to enable translation features. Since Qt translates strings at run-time based on the class they are associated with and lupdate looks for translatable strings in the source code, non-Qt classes must use mechanisms that also provide this information.

One way to do this is to add translation support to a non-Qt class using the Q_DECLARE_TR_FUNCTIONS() macro; for example:

 class MyClass
 {
     Q_DECLARE_TR_FUNCTIONS(MyClass)

 public:
     MyClass();
     ...
 };

This provides the class with tr() functions that can be used to translate strings associated with the class, and makes it possible for lupdate to find translatable strings in the source code.

Alternatively, the QCoreApplication::translate() function can be called with a specific context, and this will be recognized by lupdate and Qt Linguist.

Translator Comments

Developers can include information about each translatable string to help translators with the translation process. These are extracted when lupdate is used to process the source files. The recommended way to add comments is to annotate the tr() calls in your code with comments of the form:

//: ...

or

/*: ... */

Examples:

 //: This name refers to a host name.
 hostNameLabel->setText(tr("Name:"));

 /*: This text refers to a C++ code example. */
 QString example = tr("Example");

In these examples, the comments will be associated with the strings passed to tr() in the context of each call.

Adding Meta-Data to Strings

Additional data can be attached to each translatable message. These are extracted when lupdate is used to process the source files. The recommended way to add meta-data is to annotate the tr() calls in your code with comments of the form:

//= <id>

This can be used to give the message a unique identifier to support tools which need it.

An alternative way to attach meta-data is to use the following syntax:

//~ <field name> <field contents>

This can be used to attach meta-data to the message. The field name should consist of a domain prefix (possibly the conventional file extension of the file format the field is inspired by), a hyphen and the actual field name in underscore-delimited notation. For storage in TS files, the field name together with the prefix "extra-" will form an XML element name. The field contents will be XML-escaped, but otherwise appear verbatim as the element's contents. Any number of unique fields can be added to each message.

Example:

 //: This is a comment for the translator.
 //= qtn_foo_bar
 //~ loc-layout_id foo_dialog
 //~ loc-blank False
 //~ magic-stuff This might mean something magic.
 QString text = MyMagicClass::tr("Sim sala bim.");

You can use the keyword TRANSLATOR for translator comments. Meta-data appearing right in front of the TRANSLATOR keyword applies to the whole TS file.

Disambiguation

If the same translatable string is used in different roles within the same translation context, an additional identifying string may be passed in the call to tr(). This optional disambiguation argument is used to distinguish between otherwise identical strings.

Example:

 MyWindow::MyWindow()
 {
     QLabel *senderLabel = new QLabel(tr("Name:"));
     QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
     ...

In Qt 4.4 and earlier, this disambiguation parameter was the preferred way to specify comments to translators.

Handling Plurals

Some translatable strings contain placeholders for integer values and need to be translated differently depending on the values in use.

To help with this problem, developers pass an additional integer argument to the tr() function, and typically use a special notation for plurals in each translatable string.

If this argument is equal or greater than zero, all occurrences of %n in the resulting string are replaced with a decimal representation of the value supplied. In addition, the translation used will adapt to the value according to the rules for each language.

Example:

 int n = messages.count();
 showMessage(tr("%n message(s) saved", "", n));

The table below shows what string is returned depending on the active translation:

Active Translation
nNo TranslationFrenchEnglish
0"0 message(s) saved""0 message sauvegardé""0 messages saved"
1"1 message(s) saved""1 message sauvegardé""1 message saved"
2"2 message(s) saved""2 messages sauvegardés""2 messages saved"
37"37 message(s) saved""37 messages sauvegardés""37 messages saved"

This idiom is more flexible than the traditional approach; e.g.,

 n == 1 ? tr("%n message saved") : tr("%n messages saved")

because it also works with target languages that have several plural forms (e.g., Irish has a special "dual" form that should be used when n is 2), and it handles the n == 0 case correctly for languages such as French that require the singular.

To handle plural forms in the native language, you need to load a translation file for this language, too. The lupdate tool has the -pluralonly command line option, which allows the creation of TS files containing only entries with plural forms.

See the Qt Quarterly Article Plural Forms in Translations for further details on this issue.

Instead of %n, you can use %Ln to produce a localized representation of n. The conversion uses the default locale, set using QLocale::setDefault(). (If no default locale was specified, the system wide locale is used.)

A summary of the rules used to translate strings containing plurals can be found in the Translation Rules for Plurals document.

Translating Text That is Outside of a QObject Subclass

Using QCoreApplication::translate()

If the quoted text is not in a member function of a QObject subclass, use either the tr() function of an appropriate class, or the QCoreApplication::translate() function directly:

 void some_global_function(LoginWidget *logwid)
 {
     QLabel *label = new QLabel(
             LoginWidget::tr("Password:"), logwid);
 }

 void same_global_function(LoginWidget *logwid)
 {
     QLabel *label = new QLabel(
             QCoreApplication::translate("LoginWidget", "Password:"),
             logwid);
 }

Using QT_TR_NOOP() and QT_TRANSLATE_NOOP() in C++

If you need to have translatable text completely outside a function, there are two macros to help: QT_TR_NOOP() and QT_TRANSLATE_NOOP(). They merely mark the text for extraction by the lupdate tool. The macros expand to just the text (without the context).

Example of QT_TR_NOOP():

 QString FriendlyConversation::greeting(int type)
 {
     static const char *greeting_strings[] = {
         QT_TR_NOOP("Hello"),
         QT_TR_NOOP("Goodbye")
     };
     return tr(greeting_strings[type]);
 }

Example of QT_TRANSLATE_NOOP():

 static const char *greeting_strings[] = {
     QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"),
     QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye")
 };

 QString FriendlyConversation::greeting(int type)
 {
     return tr(greeting_strings[type]);
 }

 QString global_greeting(int type)
 {
     return QCoreApplication::translate("FriendlyConversation",
                                        greeting_strings[type]);
 }

If you disable the const char * to QString automatic conversion by compiling your software with the macro QT_NO_CAST_FROM_ASCII defined, you'll be very likely to catch any strings you are missing. See QString::fromUtf8() and QString::fromLatin1() for more information.

Using QKeySequence() for Accelerator Values

Accelerator values such as Ctrl+Q or Alt+F need to be translated too. If you hardcode Qt::CTRL + Qt::Key_Q for "quit" in your application, translators won't be able to override it. The correct idiom is:

 exitAct = new QAction(tr("E&xit"), this);
 exitAct->setShortcuts(QKeySequence::Quit);

Using Numbered Arguments

The QString::arg() functions offer a simple means for substituting arguments:

 void FileCopier::showProgress(int done, int total,
                               const QString &currentFile)
 {
     label.setText(tr("%1 of %2 files copied.\nCopying: %3")
                   .arg(done)
                   .arg(total)
                   .arg(currentFile));
 }

In some languages the order of arguments may need to change, and this can easily be achieved by changing the order of the % arguments. For example:

 QString s1 = "%1 of %2 files copied. Copying: %3";
 QString s2 = "Kopierer nu %3. Av totalt %2 filer er %1 kopiert.";

 qDebug() << s1.arg(5).arg(10).arg("somefile.txt");
 qDebug() << s2.arg(5).arg(10).arg("somefile.txt");

produces the correct output in English and Norwegian:

 5 of 10 files copied. Copying: somefile.txt
 Kopierer nu somefile.txt. Av totalt 10 filer er 5 kopiert.

Further Reading

Qt Linguist Manual, Hello tr() Example, Translation Rules for Plurals