Qt深入浅出(十六)多国语言国际化
Qt深入浅出(十六)多国语言国际化
2018年02月24日 00:40:14 吓人的猿 阅读数:160
多国语言国际化
Qt自己提供了一个种国际化方案, 生成字典文件的方法来翻译Qt应用中的tr()、translate()字符串,字典文件以”.qm”命名。
1 生成一个qm文件
新建一个GUI工程”TestHello.pro”,在UI界面上添加两个按钮,并分别将文本修改为“hello”, “china”.
修改”TestHello.pro”文件,添加如下代码:
TRANSLATIONS += TestHello.ts
编译
编译完成后,选择开始(或者win键)-> 所有应用 -> Qt5.7.0-> Qt5.7.0 for Desktop (MinGW 5.3.0 32 bit)菜单项,打开DOS命令行窗口,进入`TestHello工程目录, 执行命令:
1
2
lupdate TestHello.pro
选择开始(或者win键)-> 所有应用 -> Qt5.7.0-> Linguist 菜单项
在主界面中选择文件-> 打开, 选择TestHello.ts文件, 单击打开按钮,根据需要设置源语言和目标语言
选择要翻译的字符串,输入对应的翻译文字,单击上面Mark as done item按钮
选择文件-> 发布菜单项. 或者在命令行输入lrelease TestHello.pro, 在工程目录里面就生成了一个TestHello.qm文件.
修改源代码如下:
main.cpp
1
2

include “mainwindow.h”

3

include

4

include

5
6
int main(int argc, char argv[])
7
{
8
QApplication a(argc, argv);
9
QTranslator
translator = new QTranslator; \生成一个字典对象
10
translator->load(“D:\workspace\TestHello.qm”); \加载一个字典文件
11
a.installTranslator(translator); \安装字典文件
12
MainWindow w;
13
w.show();
14
return a.exec();
15
}
2 时实切换qm文件
事先我们编好三本字典分别是lang_zh.qm中文字典、lang_en.qm英文字典、lang_yy.qm粤语字典。
Widget.h
1
2

ifndef WIDGET_H

3

define WIDGET_H

4
5

include

6

include

7

include

8
9
class Widget : public QWidget
10
{
11
Q_OBJECT
12
13
public:
14
Widget(QWidget parent = 0);
15
~Widget();
16
void reflashLabel();
17
public slots:
18
void changeLangSlot(int);
19
private:
20
QLabel
_label;
21
QComboBox * _combobox;
22
};
23
24

endif // WIDGET_H

Widget.cpp
1
2

include “widget.h”

3

include

4

include

5

include

6

include

7

include

8
9
Widget::Widget(QWidget parent)
10
: QWidget(parent)
11
{
12
QVBoxLayout
vBox = new QVBoxLayout;
13
combobox = new QComboBox; //用到一个下拉选择控件
14
_label = new QLabel;
15
this->setLayout(vBox);
16
vBox->addWidget(_label, 5);
17
vBox->addWidget(_combobox, 1);
18
_combobox->addItem(“English”, “en”);
19
_combobox->addItem(“Chinese”, “zh”);
20
_combobox->addItem(“YueYu”, “yy”);
21
22
/
下拉选择控件被用户选择某一项后,会发射出一个带某一项索引的信号/
23
connect(_combobox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeLangSlot(int)));
24
reflashLabel();
25
}
26
void Widget::reflashLabel()
27
{
28
_label->setText(tr(“LABEL_HELLO”, “hello”));
29
}
30
31
void Widget::changeLangSlot(int index)
32
{
33
QString name = _combobox->itemData(index).toString();
34
static QTranslator* tran = NULL;
35
36
if(!tran)
37
{
38
QApplication::instance()->removeTranslator(tran); //移除已经安装的字典文件
39
delete tran;
40
tran = NULL;
41
}
42
/
重新安装字典/
43
tran = new QTranslator;
44
tran->load(“D:/workspace/untitled11/lang
“ + name + “.qm”);
45
QApplication::instance()->installTranslator(tran);
46
reflashLabel();
47
}
48
49
Widget::~Widget()
50
{
51
52
}
已使用 Microsoft OneNote 2016 创建。