C

Qt Quick Ultralite translation Example

Demonstrates how to implement translation in a Qt Quick Ultralite application.

Overview

The translation example uses the techniques described in the Internationalization and Localization with Qt Quick Ultralite topic. It demonstrates how to embed localized resources into your application and how UI language changes could be done at runtime using existing QML API.

By tapping the screen, user is able to switch between available languages (english, norwegian, latvian, japanese, arabic, thai). Changing the application language updates the flag image, and the Text and StaticText items. Only StaticText renders complex scripts correctly with the static font engine.

The application provides the following options:

  • Elide text - Elides text in the Text item only. The StaticText item is not affected by this option as eliding text is not supported on it.
  • Show text background - Adds a pink background to the text items, to visualize at what boundaries the text will be elided.

Target platforms

Project structure

CMake project file

The CMakeLists.txt for this example defines three separate CMake targets:

  • translation_all - Builds the application with all translations.
  • translation_lv - Builds the application with only latvian translation.
  • translation_spark - Builds the application with all translations and the Monotype Spark font engine.
QmlProject file

As text used by the application are rendering glyphs that are not present in the default font shipped with Qt Quick Ultralite, a custom font is added to the project in each target.

    // Qul ships some default fonts. Since they don't contain glyphs for
    // all the characters that are needed for this application,
    // add some extra fonts.
    FontFiles {
        files: [
            "fonts/kosugi/Kosugi-Regular.ttf",
            "fonts/sarabun/Sarabun-Regular.ttf"
        ]
    }
translation_all

This application variant includes all the available translations.

    TranslationFiles {
        files: [
            "translation.ar_SA.ts",
            "translation.ja_JP.ts",
            "translation.lv_LV.ts",
            "translation.nb_NO.ts",
            "translation.th_TH.ts"
        ]
    }

    // Qul ships some default fonts. Since they don't contain glyphs for
translation_lv

Here, only the latvian language is made available and set as the default application language.

    TranslationFiles {
        files: ["translation.lv_LV.ts"]
        MCU.omitSourceLanguage: true
    }
translation_spark

This application variant is almost identical to translation_all, except it's using Monotype Spark font rendering engine.

...
        TranslationFiles {
                files: [
                "translation.ar_SA.ts",
                "translation.ja_JP.ts",
                "translation.lv_LV.ts",
                "translation.nb_NO.ts",
                "translation.th_TH.ts"
                ]
        }

        FontFiles {
                files: [
                        "fonts/monotype/TranslationsSampleFontmap.fmp"
                ]
        }

        MCU.Config {
                fontEngine: "Spark"
                defaultFontFamily: "arabic-style-font"
                fontCacheSize: 1 // Disable the cache
        }
...
Application UI

The translation.qml file defines the application's user interface.

To mark the localizable strings use the qStr() method.

StaticText {
    width: root.textMaxWidth
    text: qsTr("orange", "color")
}
StaticText {
    width: root.textMaxWidth
    text: qsTr("orange", "fruit")
}
StaticText {
    width: root.textMaxWidth
    text: qsTr("sunrise")
}
StaticText {
    // This string is not translated in the .ts files and
    // will just fall back to the source string.
    width: root.textMaxWidth
    text: qsTr("hello")
}

The Qt.uiLanguage property is the central point of interest when working with translations.

If application is built with only one of the available languages, Qt.uiLanguage property will be empty.

// Disable language switching when this is compiled with
// a single language.
Component.onCompleted: allowLangSwitch = (Qt.uiLanguage == "")

Change the Qt.uiLanguage property value to change the current UI display language.

MouseArea {
    anchors.fill: parent
    onClicked: {
        if (!root.allowLangSwitch)
            return

        var lang = Qt.uiLanguage
        switch (lang) {
            case "nb_NO": lang = "lv_LV"; break;
            case "lv_LV": lang = "ja_JP"; break;
            case "ja_JP": lang = "ar_SA"; break;
            case "ar_SA": lang = "th_TH"; break;
            case "th_TH": lang = ""; break;
            default: lang = "nb_NO"; break;
        }
        Qt.uiLanguage = lang
    }
}

Note: Setting an empty string means using "default" language (unloading .ts file) where original texts wrapped in qStr() are used.

Translation specific images

Text.StyledText formatted strings are supported in qsTr(). This approach gives the translator flexibility to change the location of an image in the text based on the word order in the translated string.

StaticText {
    width: root.width
    topPadding: 8
    textFormat: Text.StyledText
    text: qsTr("English language (US) <img src=\"usa-flag-small-icon.png\" width=\"38\" height=\"20\">")
}

Alternatively, Image item can be used and source property can have a binding on Qt.uiLanguage.

Image {
    readonly property bool horizontalScreen: root.width > root.height
    width: horizontalScreen ? root.width / 4 : root.width / 3
    height: horizontalScreen ? root.height / 4 : root.height / 8
    // If this application is build with, for example, only one translation
    // (see translation_lv.qmlproject), then only one of flag PNGs
    // is needed in the binary (registered with the resouce system).
    // By using a function here we prevent qmltocpp from trying to
    // resolve file paths to images at build-time. Instead
    // a code is generated that will try to resolve the path to
    // image at run-time.
    source: flagForLanguage()
}

Translation files (.ts)

When the application is built for the first time, the .ts files are generated into your project's root directory.

A translation file is a plain XML file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="nb_NO">
<context>
    <name>translation</name>
    <message>
        <location filename="translation.qml" line="108"/>
        <source>English language (US) &lt;img src=&quot;usa-flag-small-icon.png&quot; width=&quot;38&quot; height=&quot;20&quot;&gt;</source>
        <oldsource>English language (US) &lt;img src=&quot;usa-flag-small-icon.png&quot;&gt; width=&quot;38&quot; height=&quot;20&quot;</oldsource>
        <translation>Norsk språk &lt;img src=&quot;norway-flag-small-icon.png&quot; width=&quot;27&quot; height=&quot;20&quot;&gt;</translation>
    </message>
    ...

You can use any text/xml editor to provide right values for the <translation> nodes. The Qt Linguist GUI editor is also a perfect choice for working with translation files.

Trigger a build of auto-generated update_translations CMake target to create or update the .ts files with new and changed translatable strings from the source code.

After editing the .ts files, rebuild your application target to update translations.

If the string wrapped with qStr() is not found in the translation file, the original (source) string will be used.

Files:

Images:

See also Internationalization and Localization with Qt Quick Ultralite.

Available under certain Qt licenses.
Find out more.