QT多语言翻译
方法
- tr()函数获取需要翻译的文本
- lupdate.exe编译生成xxx.ts文件
- linguist.exe进行翻译
- lrelease.exe生成去xxx.qm文件
示例
单一语言翻译,直接main中注册
QTranslator *translator = new QTranslator;
translator->load("lang_en.qm");
a.installTranslator(translator);//安装翻译器
多种语言
#include "widget.h"
#include "ui_widget.h"
#include <QVBoxLayout>
#include <QTranslator>
#include <QApplication>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_languageBox = new QComboBox;
m_languageBox->addItem("Chinese","zh");
m_languageBox->addItem("English","en");
m_languageBox->addItem("Latin","la");
m_languageBox->addItem("Franch","fr");
connect(m_languageBox,SIGNAL(currentIndexChanged(int)),this,SLOT(changeLanguage(int)));
//tr()函数用于获取需要翻译的文本
m_nameLabel = new QLabel(tr("快乐的威猛先生"));
m_signLabel = new QLabel(tr("人生如戏。"));
setWindowTitle(tr("测试"));
resize(400,100);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_languageBox);
layout->addWidget(m_nameLabel);
layout->addWidget(m_signLabel);
}
Widget::~Widget()
{
delete ui;
}
void Widget::changeLanguage(int index)
{
static QTranslator *translator;
if(translator){
qApp->removeTranslator(translator);
delete translator;
translator = nullptr;
}
translator = new QTranslator;
QString languageCode = m_languageBox->itemData(index).toString();
QString qmFile = "lang_"+languageCode;
if(translator->load(qmFile)){
qApp->installTranslator(translator);
}
//翻译文本——找不到则用逗号后面的
m_nameLabel->setText(tr("TXT_NAME_WORD","Happy Mr. Weimeng"));
m_signLabel->setText(tr("TXT_SIGN_WORD","Life is like a play."));
setWindowTitle(tr("TXT_TITLE_WORD","Test"));
}
注意事项
- pro文件添加,xx.ts
- g++ Maybe you forgot to setup the environment?
解决方法——https://www.cnblogs.com/ybqjymy/p/13552032.html
- lupdate.exe
- 翻译完打钩
- 点击发布