4
votes

After several weeks of on-and-off research, I still haven't found a thorough guide on how to perform translation/localization in QtQuick (as in, using the QML language, not C++ or Python).

In general, I'm asking what are the steps to properly localize a project as much in QtQuick as possible, with minimal or preferably no C++.

More specifically, there are a good number of holes I need to fill in my understanding of how QtQuick handles localization.

So far, I've:

  • Appended QT_TR_NOOP() to all of my translatable strings for translation at runtime

  • Added my file containing all strings to my .pro file using lupdate_only{SOURCES += LanguageStrings.qml}

  • Generated translation files using QtLinguist

However, I intend to implement an option for dynamically changing the language, and the only example I've seen regarding translation which wasn't entirely in C++ essentially created an instance of the project for each language, rather than changing the strings at runtime.

So, how do I change the language at runtime? Is there a variable I can set? Is it pulled from system locale? I haven't seen a solid answer on this.

Any ideas?

1

1 Answers

2
votes

You can do this with minimal C++ (at least I think this is minimal). I've done this in the past using the locale of the system the app is installed on like this (directly in main()):

QGuiApplication app(argc, argv);

QTranslator translator;

if(translator.load(":/translations/myapp_" + QLocale::system().name())) {
    app.installTranslator(&translator);
} else {
    qDebug() << "Unable to load translation";
} 

The translations need to be in the resource system for the above to work. You can of course trigger the above based on user input from QML (e.g. in the settings of your app) at run-time. Here is some example code to do this (https://wiki.qt.io/How_to_do_dynamic_translation_in_QML). I am not aware of a QML-only way to do this.

I tried something else which works, too. You can have your UI in a Loader Element and simply use the setSource functions of that element after the translator changed. I quickly put together a small example, which also includes an example of how to change UI elements outside the Loader, if that is needed (https://github.com/Conntac/qtExamples).