QT开发过程中,QObject::tr()用得比较多,尤其是需要做多语言翻译时。譬如:
QtGuiApplication1::QtGuiApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
ui.pushButton->setText(tr("你好"));
}
如果程序安装了对应的翻译文件,那么pushButton的文本会自动替换为目标语言对应的翻译。上面这种调用应付一般的开发基本足够了,但是考虑下面的情形:
QtGuiApplication1::QtGuiApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
ui.pushButton->setText(tr("你好"));
ui.pushButton_2->setText(tr("你好"));
}
假如在英文环境下,pushButton的文本要翻译为“Hello”,pushButton_2的文本要翻译成"Hi",怎么办?这个时候使用lupdate生成的ts文件中,针对两个"你好",只生成了一条翻译词条。
对于这种情况,QT称之为"
Disambiguation",看看QT是如何处理的。
Disambiguation
If the same translatable string is used in different roles within the same translation context, an additional identifying string may be passed in the call to tr(). This optional disambiguation argument is used to distinguish between otherwise identical strings.
Example:
MyWindow::MyWindow(){QLabel *senderLabel = new QLabel(tr("Name:"));QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));...In Qt 4.4 and earlier, this disambiguation parameter was the preferred way to specify comments to translators.
是的,就是tr()的第二个参数disambiguation,也就是给有歧义的翻译文本加上一个唯一标识(标识并不参与翻译),这样在执行lupdate时,就会生成多个词条了。
tr()还有第三个参数,是用来处理复数形式的。
QMessageBox::information(this, "Rich", tr("我有%n个苹果", "", n));
lupdate检测到tr()中的"%n"时,认为这是一个有复数语义的文本,生成的ts里面会按照目标语言生成复数翻译词条,譬如对于单数我们可以翻译成"I have %n apple", 而复数则要翻译成"I have %n apples". 这样,程序运行后,tr()会自动检测n值,并根据对应语言的复数规则,来判断这里是应该使用单数翻译版本还是复数翻译版本。 是不是很赞????