Codexecutor Codexecutor - 1 year ago 112
C++ Question

How to dynamically translate qt applications?

I have a program in two languages english and arabic, in files called app_en and app_ar. I am able to translate the program at the start in main using installTranslator in QApplication. My question is how can I change the language of the program with a push of a QAction?

Here is my attempt:

I have My language QAction connected to a slot which gets user's language of choose then saves it and goes to another function to install the translation. This all happens outside the QMainWindow.

void MainCore::GetAndSaveLanguage(bool){
//Getting the language the users wants.
bool OKPressed;
QString Language = QInputDialog::getItem(NULL, InputDialogString, InputDialogString + ":", Languages, 0, false, &OKPressed)
.remove(QRegExp("*(", Qt::CaseSensitive, QRegExp::Wildcard)).remove(')');

//Checking if ok button was pressed.
//Saving the languages.
Settings->setValue("Language", Language);

//Update language.

void MainCore::UpdateTranslations(QString Language){
//Setting the translation for the qt widgets.
QTranslator QtTranslator;
QtTranslator.load("qt_" + Language, QLibraryInfo::location(QLibraryInfo::TranslationsPath));

//Setting the translation for the program.
QTranslator AppTranslator;
AppTranslator.load("app_" + Language, ":/translations");

I also have on the QMainWindow a function which sets all the text of the screen like this:

void Window::SetText(){

This is called when the windows is constructed and in the changeEvent function:

void Window::changeEvent(QEvent *event){
if(event->type() == QEvent::LanguageChange){

Answer Source

the problem is you allocate your QtTranslator in the stack, and it goes out of scope in the end of UpdateTranslations

void MainCore::UpdateTranslations(QString Language)
  //Setting the translation for the qt widgets.
  QTranslator QtTranslator;
  QtTranslator.load("qt_" + Language,QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  QApplication::instance()->installTranslator(&QtTranslator); // this is a bad reference

} // QtTranslator will go out of scope

you need QtTranslator to live as long as your app is running. So one option is to allocate it in the heap

QTranslator * QtTranslator = new QTranslator;

and you need to keep a reference to QtTranslator to be able to delete it later...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download