一、.pro文件中添加支持的语言
在.pro文件中添加下面几句,支持中文和英文
TRANSLATIONS = lanague_cn.ts\
lanague_en.ts
二、通过qt语言家更新翻译生成.ts文件
完成以后在工程目录可以看到.ts文件
三、通过linguist翻译文件
打开文件
将两个文件同时选中,打开。
四、Qt语言家发布文字生成.qm文件
五、使用翻译文件进行多语言切换
为了方便多窗口同时切换,使用单例类进行,源码如下:
languageHelper.h
#ifndef LANGUAGEHELPER_H
#define LANGUAGEHELPER_H
#include <QObject>
#include <QMutex>
#include <QTranslator>
#include <QApplication>
class LanguageHelper : public QObject
{
Q_OBJECT
public:
enum language {
chinese,
english,
undefined
};
signals:
void languageChaned();
private:
explicit LanguageHelper();
~LanguageHelper();
LanguageHelper(LanguageHelper&) = delete;
LanguageHelper operator=(const LanguageHelper &) = delete;
public:
static LanguageHelper *getInstance()
{
static QMutex mutex;
mutex.lock();
if(languageHelper == nullptr)
{
languageHelper = new LanguageHelper();
}
mutex.unlock();
return languageHelper;
}
static void quit();
bool changeLanguage(language l);
private:
static LanguageHelper *languageHelper;
QTranslator* translator = nullptr;
language currentLanguage = language::undefined;
};
#endif // LANGUAGEHELPER_H
languageHelper.cpp
#include "languageHelper.h"
LanguageHelper *LanguageHelper::languageHelper = nullptr;
LanguageHelper::LanguageHelper()
{
this->translator = new QTranslator();
}
LanguageHelper::~LanguageHelper()
{
if(this->translator)
{
delete this->translator;
this->translator = nullptr;
}
qDebug()<<"~LanguageHelper";
}
void LanguageHelper::quit()
{
if(languageHelper)
delete languageHelper;
}
bool LanguageHelper::changeLanguage(language l)
{
if(l == this->currentLanguage || l == language::undefined)
return true;
bool ret = false;
switch(l)
{
case chinese:
{
if (this->translator != nullptr)
qApp->removeTranslator(this->translator);
ret = this->translator->load("E:/CompanyProjects/KPMG/winccTemp/language/Language/lanague_cn.qm");
if (ret)
{
bool install = qApp->installTranslator(this->translator);
if (install == false)
return false;
}
else
return false;
}break;
case english:
{
if (this->translator != nullptr)
qApp->removeTranslator(this->translator);
ret = this->translator->load("E:/CompanyProjects/KPMG/winccTemp/language/Language/lanague_en.qm");
if (ret)
{
bool install = qApp->installTranslator(this->translator);
if (install == false)
return false;
}
else
return false;
}break;
case undefined:
{
}break;
}
if (ret) {
this->currentLanguage = l;
emit languageChaned();
}
}
通过按钮切换语言:
void MainWindow::on_btnChinese_clicked()
{
LanguageHelper::getInstance()->changeLanguage(LanguageHelper::chinese);
}
void MainWindow::on_btnEnglish_clicked()
{
LanguageHelper::getInstance()->changeLanguage(LanguageHelper::english);
}
需要注意的是,在需要实时翻译的界面需要实现languageChaned
信号的绑定,然后调用ui->retranslateUi(this);
函数,如下:
connect(LanguageHelper::getInstance(),&LanguageHelper::languageChaned,this,
[=]()
{
ui->retranslateUi(this);
});