Qt国际化,使用的是QTranslator 类,通过
QTranslator qtTranslator;
QString language= "中文"; //显示语言
QString dir ;
if(language != "中文")
{
dir = qApp->applicationDirPath() + "/" +"language.eng.qm";
}
else
{
dir = qApp->applicationDirPath() + "/" +"language.zh_CN.qm";
}
if (qtTranslator.load(dir))
{
qApp->installTranslator(&qtTranslator);
qDebug() << "加载语言:installTranslator " << language;
}
对以上代码进行单例化
translator.h
#ifndef TRANSLATOR_H
#define TRANSLATOR_H
#include <QObject>
#include <QWidget>
#include <QSettings>
#include <QTextCodec>
#include <QDir>
#include <QTranslator>
#include <QDebug>
#include <QApplication>
class translator
{
public:
translator();
~translator();
private:
static translator *curTanslator; //翻译单例
QTranslator qtTranslator;
QString language; //显示语言
void loadTranslator(); //加载翻译文件
public:
static translator *getTranslator(); //获取翻译指针
static void setLanguage(QString lanStr);//设置显示语言
};
#endif // TRANSLATOR_H
translator.cpp
#include "translator.h"
translator *translator::curTanslator = 0; //翻译单例
//
translator::translator()
{
if(curTanslator == 0)
{
curTanslator = this;
}
QSettings settings(QDir::currentPath()+"/config.ini",QSettings::IniFormat); //读取配置文件
settings.setIniCodec(QTextCodec::codecForName("UTF-8"));
setLanguage(settings.value("deviceInfo/language","中文").toString());//设置语言
}
//
translator::~translator()
{
}
//获取翻译指针
translator *translator::getTranslator()
{
if(curTanslator == 0)
{
curTanslator = new translator();
}
return curTanslator;
}
//加载翻译文件
void translator::loadTranslator()
{
QString dir ;
if(language != "中文")
{
dir = qApp->applicationDirPath() + "/" +"language.eng.qm";
}
else
{
dir = qApp->applicationDirPath() + "/" +"language.zh_CN.qm";
}
if (qtTranslator.load(dir))
{
qApp->installTranslator(&qtTranslator);
qDebug() << "加载语言:installTranslator " << language;
}
}
//设置显示语言
void translator::setLanguage(QString lanStr)
{
if(curTanslator == 0)
curTanslator = getTranslator();
if(curTanslator->language != lanStr)
{
curTanslator->language = lanStr;
curTanslator->loadTranslator();
}
}
使用
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
translator::getTranslator();
return a.exec();
}
当需要动态切换语言时调用接口
translator::setLanguage(language);
同时在各个需要翻译的类中,重写
void deviceInfoWidget::changeEvent(QEvent *event)
{
if(event->type() == QEvent::LanguageChange)
{
//翻译更新界面
ui->retranslateUi(this);
}
else
QWidget::changeEvent(event);
}