### 代码中的可翻译字符串
#### 继承自`QObject`的类
要加上`Q_OBJECT`, 不然`context`会默认继承基类的.
> Developers subclassing QObject must use the `Q_OBJECT` macro in their class definition to override the translation context.
> ...
> If `Q_OBJECT` is not used in a class definition, the context will be inherited from the base class.
#### 非继承自`QObject`的类
给类加上`Q_DECLARE_TR_FUNCTIONS()`宏.
```c
class MyClass
{
Q_DECLARE_TR_FUNCTIONS(MyClass)
public:
MyClass()
{
QString str = tr("example");
}
// ...
};
```
#### 类外翻译
用`QObject::tr()`生成的翻译文件里没有`contenxt`可能会出现冲突, 所以更倾向于用`QApplication::translate()`.
> If the quoted text is not in a member function of a QObject subclass, use either the tr() function of an appropriate class, or the QCoreApplication::translate() function directly.
1、加载翻译文件
代码中用QTranslator加载lrealse生成的.qm文件.
QTranslator translator();
if (translator.load("foo.qm"))
qApp->installTranslator(&translator);
2、相关工具
lupdate
扫描源代码生成翻译文件(.ts)
$ lupdate -source-language en_US -target-language zh_CN ./src -ts ./ts/translation.ts
linguist
用于编辑lupdate生成的翻译文件(.ts), 图形界面没什么可说的. 不过它的自动翻译(Batch Transition)功能还是值得一提的.
Use the batch translation feature of Qt Linguist to automatically translate source texts that are also in a phrase book.
- 界面入口:
Edit > Batch Translation - Phase Book(翻译词典):
Phrases > New Phrase Book
Phrases > Open Phrase Book
Phrases > Edit Phrase Book
lrease
把.ts文件编译为QTranslator的资源文件.qm
$ lrease ts-file -qm qm-file
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓