背景:
需要界面实现动态国际化,一键点击切换中英文或其他语言。
前提:
已经完成了整个界面的翻译,拿到匹配的ts翻译文件,注意:要保证界面切换后,翻译的全覆盖,要保证任何需要反应的地方,都用到了tr("")包含,不然Linguist会捕捉不到。.ts文件的生成参考下文。
Qt中英文切换(国际化)_雲烟的博客-CSDN博客
工具:
假设已经拿到a.qm b.qm c.qm三个翻译文件
#include <QtCore/QObject>
#include <QtCore/QTranslator>
class LanguageManager:public QObject{
Q_OBJECT
public:
~LanguageManager() override = default;
void setLanguage(const QString &language);
QString getLanguage();
void addLangFile(const QString &name);
void removeLangFile(const QString &name);
void reload();
static LanguageManager *getInstance(){
if(!instance){
instance = new LanguageManager;
}
return instance;
}
signals:
void languageChanged(const QString &lang);
privite:
LanguageManager();
privite:
static LanguageManager *instance;
QString baseDir;
QList<QString> langFiles;
QList<QTranslator *> translations;
}
#include "Languagemanager.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDebug>
#include <QStringBuilder>
#include <configFile.h>
LanguageManager *LanguageManager::instance = nullptr;
void LanguageManager::setLanguage(const QString &language)
{
//写配置文件保存
SystemConfig sc;
auto ov = sc.value("qt/language");
sc.setValue("qt/language",language);
if(ov!=language){
reload();
emit languageChanged(language);
}
}
QString LanguageManager::getLanguage()
{
SystemConfig sc;
return sc.value("qt/language").toString();
}
void LanguageManager::addLangFile(const QString &name)
{
if(name.isEmpty()){
return;
}
langFiles.append(name);
}
void LanguageManager::removeLangFile(const QString &name)
{
if(name.isEmpty()){
return;
}
langFiles.removeOne(name);
}
void LanguageManager::reload()
{
auto lang = getLanguage();
QString qmBase = QApplication::applicationDirPath() + "/" + baseDir;
if(!qmbase.isEmpty() && !qmBase.endsWith("/")){
qmBase += "/";
}
if(!translations.isEmpty()){
for(auto const t:translations){
QCoreApplication::removeTranslator(t);
t->deleteLater();
}
translations.clear();
}
for(auto const &qm:langFiles){
auto *t = new QTranslator(this);
if(t->load(qmBase % qm % "_" % lang)){
translations.append(t);
QCoreApplication::installTranslator(t);
}else{
qDebug()<<"load error:"<<qm<<", language"<<lang;
}
}
}
LanguageManager::LanguageManager (): baseDir("lang"){}
使用:
在界面切换的按键或者条目里直接调用即可:
LanguageManager::getInstance()->setLanguage("english");
注意:该调用界面要重载changeEvent()保证界面即刻生效。文章来源:https://www.toymoban.com/news/detail-684088.html
protected:
void changeEvent(QEvent *evt) override ;
void MainPanel::changeEvent(QEvent *evt) {
if (evt->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
}
QWidget::changeEvent(evt);
}
至此,界面即可看到变化,中英文动态切换完成!文章来源地址https://www.toymoban.com/news/detail-684088.html
到了这里,关于Qt 动态中英文切换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!