|  | Home · All Classes · All Functions · Overviews

[Previous: Internationalization with Qt] [Internationalization with Qt] [Next: Translation Rules for Plurals]

# Writing Source Code for Translation

- The Basics
- Defining a Translation Context
- Using tr() to Obtain a Translation
- Translator Comments
- Adding Meta-Data to Strings
- Disambiguation
- Character Encodings
- Handling Plurals
- Enabling Translation
- Further Reading

### The Basics

Developers use the tr() function to obtain translated text for their classes, typically for display purposes. This function is also used to indicate which text strings in an application are translatable.

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 the Enabling Translation section below.

### 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.

### 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.");

Meta-data appearing right in front of a magic TRANSLATOR comment 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.

### Character Encodings

You can set the encoding for the source text by calling QTextCodec::setCodecForTr(). By default, the source text is assumed to be in Latin-1 encoding.

### 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
--- | ---
n | No Translation | French | English
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. See the Qt Linguist Manual for details.

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 "C" locale is used.)

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

### Enabling Translation

Typically, your application's `main()` function will look like this:

     int main(int argc, char *argv[])
     {
         QApplication app(argc, argv);

         QTranslator qtTranslator;
         qtTranslator.load("qt_" + QLocale::system().name(),
                 QLibraryInfo::location(QLibraryInfo::TranslationsPath));
         app.installTranslator(&qtTranslator);

         QTranslator myappTranslator;
         myappTranslator.load("myapp_" + QLocale::system().name());
         app.installTranslator(&myappTranslator);

         ...
         return app.exec();
     }

Note the use of QLibraryInfo::location() to locate the Qt translations. Developers should request the path to the translations at run-time by passing QLibraryInfo::TranslationsPath to this function instead of using the `QTDIR` environment variable in their applications.

### Further Reading

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

[Previous: Internationalization with Qt] [Internationalization with Qt] [Next: Translation Rules for Plurals]