- 在.pro文件中添加以下代码并编译(分别是英文,中文,拉丁文)
TRANSLATIONS = lang_en.ts \
lang_zh.ts \
lang_la.ts
- 点击Qt 5.13.1(MinGW 7.3.0 32-bit)[版本对应就行],运行命令lupdate projectName.pro命令,生.ts文件
- 点击Linguist 5.13.1(MinGW 7.3.0 32-bit),进行文件转换 ,分别打开.ts文件,然后对每个字符进行翻译,生成.qm文件。翻译好文件,点击第一个图标进行确认保存。
源码文件:
//.h文件
private slots:
void changeLang(int index);
private:
void createScreen();
void changeTr(const QString& langCode);
void refershLabel();
QComboBox* combo;
QLabel* label;
//.cpp文件
void LangSwitch::createScreen(){
combo = new QComboBox;
combo->addItem("English","en");
combo->addItem("Chinese","zh");
combo->addItem("Latin","la");
label = new QLabel;
refershLabel();
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(combo,1);
layout->addWidget(label,5);
setLayout(layout);
connect(combo,SIGNAL(currentIndexChanged(int)),this,SLOT(changeLang(int)));
changeLang(0);
}
void LangSwitch::refershLabel(){
label->setText(tr("TXT_HELLO_WORLD","Hello World"));
}
void LangSwitch::changeLang(int index){
QString langCode = combo->itemData(index).toString();
changeTr(langCode);
refershLabel();
}
void LangSwitch::changeTr(const QString &langCode){
static QTranslator* translator;
if(translator != NULL){
qApp->removeTranslator(translator);
delete translator;
translator = NULL;
}
translator = new QTranslator;
QString qmFilename = "lang_" + langCode;
if(translator->load(QString("C:/Users/adminstrator/Desktop/TestHello/")+qmFilename)){
qApp->installTranslator(translator);
}
}