c – 如何动态翻译qt应用程序?

我有一个英语和阿拉伯语两种语言的程序,名为app_en和app_ar.我可以使用QApplication中的installTranslator在main中开始翻译程序.我的问题是如何通过推动QAction来改变程序的语言?

这是我的尝试:

我将我的语言QAction连接到一个插槽,该插槽获取用户选择的语言,然后将其保存并转到另一个功能来安装翻译.这一切都发生在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);
}

我还在QMainWindow上有一个函数,它设置屏幕的所有文本,如下所示:

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

在构造窗口和changeEvent函数时调用它:

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

最佳答案 问题是你在堆栈中分配你的QtTranslator(相同的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的引用以便以后删除它…

点赞