February 2021

Automatic translation reloading in the Qt

Professional desktop applications require translations. The Qt framework has great support for translation like special CMake functions and Qt Linguist tool. Despite this fact, after translation is updated in the Qt Linguist, the person who is editing the translation must take some steps to view results of his/her work in the application. Below I will demonstrate how to make the work of the translator easier.

First of all we want to detect file changes. Qt has a special class called QFileSystemWatcher for doing this kind of job. We pass files (or directories) we want to monitor to the constructor of QFileSystemWatcher. Then we set the handler.

#include <QFileSystemWatcher>
#define COMMON_DIR "../common/"
#define SOURCE_DIR "../../src/myapp/"
// Some place of application initialization, in my case it was
// constructor of CApplication (derived form QApllication)
QStringList paths =
   COMMON_DIR "myapp_en_US.qm",
   COMMON_DIR "myapp_pl_PL.qm",
   SOURCE_DIR "myapp_en_US.ts",
   SOURCE_DIR "myapp_pl_PL.ts",

m_watcher = new QFileSystemWatcher(paths, m_mainWindow);
    connect(m_watcher, SIGNAL(fileChanged(QString)), m_mainWindow, SLOT( HandleFileChanged(QString) ));

After the file system watcher is in place we must write our handler. Below you can see the contents of this method.

void CMainWindow::HandleFileChanged(const QString& filename )
        //code for loading the translation
    else if(filename.endsWith(".ts"))
        QProcess cmdProcess;
        cmdProcess.start("cmd.exe", {"/c release_translations.bat"});

As you can see after *.ts file is modified we start a batch file. This batch file calls lrelease executable, which converts xml based ts files into binary qm files. Normally this step is done during the build. Below you can see the contents of release_translations.bat file.

SET PATH=%PATH%;C:\Qt\5.15.2\msvc2019_64\bin

lrelease src\myapp\myapp_en_US.ts -qm bin\common\myapp_en_US.qm
lrelease src\myapp\myapp_pl_PL.ts -qm bin\common\myapp_pl_PL.qm

As an alternative to using batch file one could call lrelease application directly from Qt application. In my case I decided to use batch file as proxy, where I can modify lrelease settings, without modifying the code.

After code is up and running user can just press Ctrl+S in the Qt Linguist and the new translation will jump right into the application he/she is working on.