Sunday, January 29, 2012

Translating QML Applications: The Full Story

1. In the QML code, text should be inside qsTr(), e.g. instead of

    Label {text: "Hello"}

write

    Label {text: qsTr("Hello")

2. Make a directory containing the translations, let's call it translations. Add let's assume the QML sources are in the directory qml

3. Collect the texts to be translated into translations/<language>.ts, using the lupdate command. The following command

    lupdate qml -ts translations/hu.ts translations/es.ts

will recursively collect texts from source code in qml, into hu.ts and es.ts.

Name the translation files after the name of the target language, like es.ts (Spanish) or hu.ts (Hungarian).  Use two-letter language codes as in ISO 639-1. See http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes.

To make a country-specific translation variant, append the two-digit ISO country code after the language code, for example hu_HO.ts (the Hungarian dialect spoken in Honduras).

If lupdate is not found on the PATH, find it in the Qt SDK. I have a version in ~/QtSDK/Desktop/Qt/473/gcc/bin for example

4. Open the .ts files with the Qt translation tool Linguist. Assuming Qt SDK on Mac, it is in ~/QtSDK/Linguist.app/Contents/MacOS/Linguist

Using Linguist, set the .ts file's language and country, and translate. Make sure all texts are translated, and translations are marked "Done" (so there is a check mark in front of them)

5. When done with translating, release the translations (File → Release). "Releasing" in this context means converting the translation file to a compact binary, which has the same name as the original, but with the extension ".qm". For example, hu.ts will be released as hu.qm

6. Create a resource file translations.qrc and add it to the project

7. Add the released translations to this resource file, so it contains

    /
      translations/hu.qm
      translations/es.qm

8. Finally in main(), activate the translation corresponding to the current language:

#include <QTranslator>
#include <QLocale>

int main(int argc, char *argv[]) {
    QApplication app;
    QString locale = QLocale::system().name();
    QTranslator translator;
    if (translator.load(locale, ":/translations")) {
        app.installTranslator(&translator);
    } else {
        // Could not load translation
    }
    ...
}


No comments:

Post a Comment