[Solved] How do I localize a Qt qmldir plugin?
(cross-posting from my StackOverflow question)
My app has a GUI written in QML and we've successfully internationalized it using qsTr() and .ts/.qm files. Now we're adding third-party plugin support via the qmldir API. In the .qml files of the plugin, qsTr() works correctly only if the translation is already in the host application's .ts files. How can a third-party QML author add localized strings to their qmldir plugin?
I'll take stab at answering my own question. The plugin should include a DLL/dylib/so component that invokes QCoreApplication::installTranslator at initialization. That new translator should load localization resource file(s) from the plugin's folder. But the plugin author should beware that any translations provided by the plugin will take precedence over the translations provided by the host app because the translators are consulted in reverse order of installation.
Does this sound right? Thanks in advance.
I just replied to you in stackoverflow, your solution is right, I copied my answer too:
I created a Translator class to organize and load translations, I have a QVariantMap that holds language name and file name, then when I create my Translator I have to provide the source directory since that is a requirement to load translations, my class also takes care of storing in QSettings last language used.
Now, to answer your question, you can always translate the exact same way as if it was a regular application, on your project file you will have to add something like this:
1 - List all your possible translations
TRANSLATIONS = \ translation_sp.ts \ translation_fr.ts
2 - Run lupdate to generate the actual translation files
3 - Run lrelease
Translate with linguist and create the actual translations, this will generate translation_sp.qm and translation_fr.qm
4 - Deploy translations with your plugin
Once you have the qm files deploy them with your plugin, ideally you could standardize the naming, maybe always using plugin_XX.qm
5 - Load plugin translation in application
To do this you will have to know the path to the translation file and the filename, so if your plugin is installed in the Qt default directories and you standardized the translation filenames this should be simple
qTranslator.load("plugin_XX.qm", "PATH_TO_TRANSLATION_FILE") app->installTranslator(qtTranslator);
I simplified this in my class, here is the source code if you want to take a look
And here's how you use it:
Translator translator(app.data(), "PATH_TO_TRANSLATION"); translator.addTranslation("SP", "plugin_XX.qm"); engine.rootContext()->setContextProperty("translator", &translator);
You can install multiple translators, so it will work for your application and your plugins, when I wrote my class I was not expecting different sources but you can modify so every time you add a translation it will take a 2 letter code for the language, the filename and the path to it.
Hope this helps!