How to dynamically translate Qt applications?

I have a bilingual program in English and Arabic, in files called app_en and app_ar. I can translate the program at the beginning to main using installTranslator in QApplication. My question is: how can I change the program language by pressing QAction?

Here is my attempt:

I have my own QAction language connected to a slot that selects the user's language, then saves it and switches to another function to set the translation. All this happens outside of 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.
    if(OKPressed){
        //Saving the languages.
        Settings->beginGroup("Settings");
        Settings->setValue("Language", Language);
        Settings->endGroup();

        //Update language.
        UpdateTranslations(Language);
     }
}

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);

    //Setting the translation for the program.
    QTranslator AppTranslator;
    AppTranslator.load("app_" + Language, ":/translations");
    QApplication::instance()->installTranslator(&AppTranslator);
}

I also have a QMainWindow function that sets the entire screen text as follows:

void Window::SetText(){
     Menu->setTitle(tr("File"));
     ...
}

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

void Window::changeEvent(QEvent *event){
    if(event->type() == QEvent::LanguageChange){
        SetText();
    }else{
        QWidget::changeEvent(event);
    }
}
+4
source share
1

, QtTranslator (Same for AppTranslator) 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

, QtTranslator , . , -

QTranslator * QtTranslator = new QTranslator;

QtTranslator, ...

+1

Source: https://habr.com/ru/post/1654231/


All Articles