VS+QT实现语言自动切换

来源:互联网 发布:皮蓬生涯数据 编辑:程序博客网 时间:2024/05/21 08:50

需要在被翻译的字符串前加tr标示,如QString=tr(hello world);这很重要,因为翻译工具会把源码中tr标识的字符串提取出来,翻译成其他语言,如果没有用tr标识的,不会被工具提取。在界面中输入的文字,默认已经是加上tr的了,所以在翻译时也能看见。建议:在程序中的字符串使用英文,汉语等通过多国语翻译来实现,而不要采取把汉字写在代码中。

实现语言切换要用到qm文件,而要创建qm文件,就必须有ts文件,而在QtCreator中存在Pro文件。通过pro文件可以转化成ts文件,转化的方式为:lupdate myproject.pro。通过ts文件转化成qm文件,转化方式是:lrelease myproject.ts,这样就生成了一个qm文件。

在VS+QT中,可能有的环境下不能创建pro文件,转化的源头没有了。所以我选择的方式是自己写ts文件,下面看一下ts文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="zh_CN">
<context>
    <name>MainWidget</name>
    <message>
        <location filename="main_widget.cpp" line="43"/>
        <source>main widget</source>
        <translation>主界面</translation>
    </message>
    <message>
        <location filename="main_widget.cpp" line="44"/>
        <source>welcome to Qt</source>
        <translation>欢迎分享、交流,Qt群:</translation>
    </message>
    <message>
        <location filename="main_widget.cpp" line="45"/>
        <source>setting</source>
        <translation>设置</translation>
    </message>
    <message>
        <location filename="main_widget.cpp" line="46"/>
        <source>ok</source>
        <translation>确定</translation>
    </message>
    <message>
        <location filename="main_widget.cpp" line="47"/>
        <source>cancel</source>
        <translation>取消</translation>
    </message>
</context>
</TS>

下面介绍一下这个ts文件,这是一个xml文件格式,在其中主要的格式是:

<message>
        <location filename="main_widget.cpp" line="47"/>
        <source>cancel</source>
        <translation>取消</translation>
 </message>

1、location filename=“main_widget.cpp line="47”其中指定了所在文件的文件名和所在的行号

2、<source>cancel</source>在程序中比如settext中,要设置cancel值。这个会自动转化成汉语“取消”

3、<translation>取消</translation>要转化成的文字

ts文件是创建完成了,直接转化就行了。

下面介绍一个怎么使用qm文件:

1、加载qm文件

QApplication app(argc, argv);

QTranslator translator;  
// 加载当前目录下的语言文件
translator.load(QString(":/qm/main_widget_") + language_suffix, ".");  
// 设置语言切换过滤器
app.installTranslator(&translator); 

app.exec();

2、动态切换过程

就是再用translator在load一个需要加载的qm文件,然后调用settext就可以自动的进行转化。

下面上传了一个例子供大家参考:

http://download.csdn.net/detail/zdongfuyu/9319865

0 0