1. main.cpp加入代码
#include <QTranslator>
QTranslator translator;
translator.load("hellotr_la");
app.installTranslator(&translator);
注:代码放入QApplication初始化之后,窗口元素显示之前。最佳方案是紧跟QApplication之后
特别注意:translator.load()有多个重载函数,其中均包含QM文件路径。在QT Creator中,使用lupdate
和linguist
命令生成ts和qm文件时,默认位置为pro文件所在位置。如果load函数仅指明QM文件,则运行时因找不到QM文件而不能正常显示翻译文本。解决方法有二:一是第二个参数直接使用QM文件的绝对路径;二是将QM文件拷贝到debug或release文件夹中,如果放在根目录下,则第二个参数可省略,否则可以使用相对路径指明
例如:我的项目源文件路径为:
C:\Qt\Qt5.5.1\Examples\Qt-5.5\linguist\hellotr
编译出来的debug文件夹路径为:
C:\Qt\Qt5.5.1\Examples\Qt-5.5\linguist\build-hellotr-Desktop_Qt_5_5_1_MSVC2013_32bit-Debug
我的项目编译出来的QM为hellotr_la.qm
那么有如下三种可行方式:
1.如果QM文件就放在源文件路径下:translator.load("hellotr_la","C:/Qt/Qt5.5.1/Examples/Qt-5.5/linguist/hellotr")
2.如果QM文件放在debug文件夹路径根目录下:translator.load("hellotr_la")
3.如果QM文件放在debug文件夹里面的debug文件夹里(与EXE文件同位置):translator.load("hellotr_la","./debug")
因为最终是要打包成单一文件发布的,这里推荐第三种方式
2. xxx.pro加入代码
TRANSLATIONS = hellotr_la.ts
3. hellotr_la.ts文件建立
执行命令
lupdate -verbose hellotr.pro
得到文件的内容
<!DOCTYPE TS><TS>
<context>
<name>QPushButton</name>
<message>
<source>Hello world!</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
4.翻译文本
执行命令
linguist hellotr_la.ts
输入译文后,先前的ts文件中内容将变为
<translation>Orbis, te saluto!</translation>
5. 获得qm文件,运行程序
运行Qt Linguist (对于单一ts文件), 或使用命令lrelease
生成QM文件.生成后在Qt Linguist中通过File|Release
和 Save
保存文件. 运行程序即可.
注:命令执行在“开始”-“所有程序”-“QT5.5 32-bits for desktop (msvc2013)”这里可看到具体QT版本
**6. 拷贝QM文件用的脚本文件
@echo off
copy D:\qgroundcontrol\BLZKGroundControl.qm D:\build-qgroundcontrol-Desktop_Qt_5_5_1_MSVC2013_32bit-Release\release
copy D:\qgroundcontrol\BLZKGroundControl.qm D:\build-qgroundcontrol-Desktop_Qt_5_5_1_MSVC2013_32bit-Release
copy D:\qgroundcontrol\BLZKGroundControl.qm D:\build-qgroundcontrol-Desktop_Qt_5_5_1_MSVC2013_32bit-Debug
copy D:\qgroundcontrol\BLZKGroundControl.qm D:\build-qgroundcontrol-Desktop_Qt_5_5_1_MSVC2013_32bit-Debug\debug
@echo off