Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Qt application with dinamic language (QTranslator) does not work



  • I have a Qt application and I need to change language at runtime. I am using QTranslator and .qm files. The language is loaded properly but my widgets don't show the text.

    Y have 'MyClass..cpp' (inherits QMainWindow):

    MyClass::MyClass()
    {
       ...
       selectLanguage("en");
    
       m_pLabel = new QLabel(tr("User"));
       m_pLabel->show();
       ...
    }
    
    void MyClass::selectLanguage(QString language) {
    
       QString sTranslationFile = QString("texts_%1").arg(language);
    
       QTranslator translator;
       //translator.load(":/translations/" + sTranslationFile);
       translator.load(sTranslationFile, ":/translations/");
    
       if (qApp->installTranslator(&translator))
           qDebug() << "Ok";
     }
    
     void MyClass::changeEvent(QEvent *pEvent)
     {
         if(pEvent)
         {
             switch(pEvent->type())
             {
                   case QEvent::LanguageChange:
                      retranslate();
                      break;
               }
         }
    
         QMainWindow::changeEvent(pEvent);
     }
    
     void MyClass::retranslate()
     {
      qDebug() << "retranslate";
    
      if (m_pLabel)
         m_pLabel->setText(tr("User"));
     }
    

    In 'myProject.pro':

     ...
     QMAKE_POST_LINK = lrelease.exe myProject.pro
     ...
     RESOURCES += \
         resources/resources.qrc
    
     TRANSLATIONS += resources/translations/texts_en.ts \
                     resources/translations/texts_es.ts
     ...
     DISTFILES += \
          ...
          resources/translations/texts_en.qm \
               resources/translations/texts_es.qm
    

    In 'resources.qrc':

     ...
     translations/texts_en.qm
     translations/texts_es.qm
    

    In 'texts_en.ts':

     <!DOCTYPE TS><TS>
     <context>
         <name>MyClass</name>
         <message>
             <source>User</source>
             <translation>UserEn</translation>
         </message>
         <message>
             <source>Group</source>
             <translation>GroupEn</translation>
         </message>
     </context>
     </TS>
    

    Language is loaded ("Ok" appears) and "retranslate" is called, but the label does NOT show "UserEn", but "User"...

    I call 'selectLanguage("es")' after a while, but the same...

    I hope somebody could help me.

    Thanks in advance,

    Diego



  • @Diego-Donate said:

    translator.load(sTranslationFile, ":/translations/");

    How do you know the language loaded properly if you didn't test the return value of translator.load?


Log in to reply