c++qt6qt-linguist

How to translate a program into a language with QtLinguist in C++?


I wrote code on QtCreator to translate the GUI of my application into English and Spanish. This application was written in French. The .ts translation files have been generated. And I translated strings to English on QtLinguist (but not Spanish), and I ticked the fields with a green arrow to show that I was sure of the translation. But when I generated the files .qm thanks to lrelease, the IDE wrote: Updating 'C:/Users/user/Documents/ZeroClassGenerator/zeroclassgenerator_en.qm'...

Generated 3 translation(s) (3 finished and 0 unfinished) Updating 'C:/Users/user/Documents/ZeroClassGenerator/zeroclassgenerator_es.qm'...

Generated 0 translation(s) (0 finished and 0 unfinished) Ignored 3 untranslated source text(s) "C:\QtSdk2\6.2.1\mingw81_64\bin\lrelease.exe" finished But the text to be translated has not been translated into English. However, I put the .qm file in the same folder as the executable of my software and I wrote the following code in the main file:

#include "FenPrincipale.h"
#include <QApplication>
#include <QTranslator>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTranslator translator;
    
    translator.load("zeroclassgenerator_en");
    a.installTranslator(&translator);
    FenPrincipale fenetre;
    fenetre.show();
    return a.exec();
}

Since that code didn't work, I wrote this one.

#include "FenPrincipale.h"
#include <QApplication>
#include <QTranslator>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTranslator translator;
    
   if( translator.load("zeroclassgenerator_en"))
    a.installTranslator(&translator);
    FenPrincipale fenetre;
    fenetre.show();
    return a.exec();
}

I don't know where I went wrong.


Solution

  • What probably happens is that QTranslator::load fails; since you didn't specify an absolute path, nor did you pass a directory as second argument, it will only try to find the file in your current working directory.

    To make this more robust, you should a) specify the directory as second argument, and b) check the return value of installTranslator():

    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QTranslator translator;
     
        if (!translator.load("zeroclassgenerator_en", QApplication::applicationDirPath()))
            qWarning("Could not load translation file");
        a.installTranslator(&translator);
        FenPrincipale fenetre;
        fenetre.show();
        return a.exec()
    }