toussa
toussa

Reputation: 1098

Why my C++ Qt UI got translated but not my QStrings in my program?

I needed to translate my english UI in french, so I did all the necessary with .ts and .qm files, load it in the QTranslator class, and install it to the QApplication:

//in the InterfaceWidget constructor:
QTranslator myappTranslator;
bool loaded = myappTranslator.load("myApp_" + QLocale::system().name());
qDebug()  << "Is translation file loaded?" << loaded; // RETURNS TRUE
QApplication::installTranslator(&myappTranslator);
ui.setupUi(this);
ui.retranslateUi(this); //works, it translates the UI

Later, I create and attach to the InterfaceWidget another Widget (in a tab) called ConfigurationTabUI :

m_ConfigurationTabUI = new ConfigurationTabUI(ui.configTab);

The corresponding UI is also translated to french, correctly.

And here is my problem: in the ConfigurationTabUI's methods, it doesn't work when I try to translate a simple QString:

void ConfigurationTabUI::on_ValidButton_clicked(){

    QString msg(ConfigurationTabUI::tr("message to translate"));
    qDebug() << "translated string: " << msg; // NOT TRANSLATED
}

I really have no clue why... Thanks for your help.

Note: I Use Qt5.2 and I double checked that the .ts file contains the right translated string.

Upvotes: 2

Views: 1755

Answers (1)

toussa
toussa

Reputation: 1098

Ok, I found the problem, it's just a dumb oversight:

QTranslator is created on the stack and not dynamically (on the heap), so the object is destroyed at the end of the method. As a result, it translates the UI because the object is still there but later, when a slot is called, nothing get translated.

Here is my code:

//in the InterfaceWidget constructor:
QTranslator* myappTranslator = new QTranslator(QApplication::instance());
bool loaded = myappTranslator->load("myApp_" + QLocale::system().name());
qDebug()  << "Is translation file loaded?" << loaded; // RETURNS TRUE
QApplication::installTranslator(myappTranslator);
ui.setupUi(this);

and in ConfigurationTabUI (which inherits from QWidget):

void ConfigurationTabUI::changeEvent(QEvent *e)
{
    if (e->type() == QEvent::LanguageChange) {
        ui.retranslateUi(this);
        reset(); //my method to reload some data in UI
    } else
        QWidget::changeEvent(e);
}

Upvotes: 2

Related Questions