c++qtqt5qtranslator

QTranslator not working when used in a if statement


I added a translation file using Qt Linguist. Then I proceeded to use QTranslator when my app is loaded:

    QTranslator translator;
    bool loaded = translator.load(":/notizie_en_UK.qm");
    bool installed = app.installTranslator(&translator);
    qDebug() << "Adding translation" << loaded << installed;

This works fine. Now I wanted to use the translation only if the system language wasn't already the default language so I did the following:

QLocale::Language phoneLang = QLocale::system().language();
qDebug() << "LANGUAGE" << phoneLang << (phoneLang != QLocale::Italian);
if(phoneLang != QLocale::Italian){
    QTranslator translator;
    bool loaded = translator.load(":/notizie_en_UK.qm");
    bool installed = app.installTranslator(&translator);
    qDebug() << "Adding translation" << loaded << installed;
}
else{
    qDebug() << "Using italian";
}

However this doesn't work. If a system in English for example, the translator doesn't work and the default language of the app is used (in this case Italian).

The output from qDebug() is:

LANGUAGE QLocale::English true

Adding translation true true


Solution

  • The problem is that the translator object is destroyed as soon as the program execution exits your if statement's body where it was defined. What you can do is:

    [..]
    if (phoneLang != QLocale::Italian) {
        QTranslator *translator = new QTranslator;
        bool loaded = translator->load(":/notizie_en_UK.qm");
        bool installed = app.installTranslator(translator);
        qDebug() << "Adding translation" << loaded << installed;
    }
    [..]
    

    However you must take care off destroying translator object yourself when necessary.

    UPDATE:

    You may define a parent of your translator that will clean up its child objects. For example:

    // The application is translator's parent.
    QTranslator *translator = new QTranslator(app);