是否可以在运行时在Qt上更改语言 [英] Is it possible to change language on Qt at runtime

查看:203
本文介绍了是否可以在运行时在Qt上更改语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我需要国际化. 假设我为不同的语言创建了多个.ts文件,例如, 德语,法语等-以及翻译的短语.

in my app I need internationalization. Say I have created several .ts file for different languages e.g., German, French, etc. - together with translated phrases.

现在,假设用户想在运行时更改语言. 使用Qt方法不可能吗?

Now, say the user wants to change the language at run time. Will it not be possible using Qt approach?

推荐答案

您应该在应用程序中具有LocaleHandler对象,并收听systemLanguageChanged()信号.

You should have a LocaleHandler object in your application and listen to the systemLanguageChanged() signal.

只要用户通过设置菜单更改语言,就会调用此信号.

This signal will be called anytime the user changes the language through the settings menu.

发生这种情况时,您应该使用以下代码将已安装的词典更新为新的词典:

When this happens you should update your installed dictionary to the new one with something like the below code:

void MyAppSettings::updateLanguage() {
    QString translations = QString("MyApp%1.qm").arg(QLocale().name());
    Application::instance()->removeTranslator(&mTranslator);
    if (mTranslator.load(translations, "app/native/qm")) {
        qDebug() << "LOAD FINISHED";
        Application::instance()->installTranslator(&mTranslator);
    } else {
        qDebug() << "COULD NOT INSTALL TRANSLATIONS " << translations;
    }
}

这将删除当前词典,并将其替换为所选系统语言的新词典.

This will remove the current dictionary and replace it with the new one for the chosen system language.

不幸的是,这还不够,因为它不会更新应用程序现有的任何屏幕.要更新QML中的现有字符串,您应该将Retranslate.onLanguageChanged添加到翻译后的字符串中.

Unfortunately this is not enough, as it will not update any existing screens you have for your app. To update existing strings in QML you should add Retranslate.onLanguageChanged to your translated string.

例如:

Label {
    text: qsTrId("header1")  + Retranslate.onLanguageChanged
}

每次转换程序更改时,这将更新上述lavel的字符串.有关更多信息,请参见: http://developer.blackberry.com/cascades/reference/bb_ cascades _qmlretranslate.html

This will update the string for the above lavel every time the translator changes. For more information see: http://developer.blackberry.com/cascades/reference/bb_cascades_qmlretranslate.html

这篇关于是否可以在运行时在Qt上更改语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆