Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Writing Source Code for Translation

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

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. Microsoft ouvre aux autres compilateurs C++ AMP, la spécification pour la conception d'applications parallèles C++ utilisant le GPU 22
  2. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 38
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. RIM : « 13 % des développeurs ont gagné plus de 100 000 $ sur l'AppWord », Qt et open-source au menu du BlackBerry DevCon Europe 0
  5. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
Page suivante

Le blog Digia au hasard

Logo

Créer des applications avec un style Metro avec Qt, exemples en QML et C++, un article de Digia Qt traduit par Thibaut Cuvelier

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.7
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web