作者:用户q4oaa53j5h | 来源:互联网 | 2023-09-04 15:48
QStringQObject::tr(constchar*sourceText,constchar*disambiguation0,intn-1)[static
QString QObject::tr ( const char * sourceText, const char * disambiguation = 0, int n = -1 ) [static]
但是实际上tr()函数是接受3个参数的。第一个参数是我们需要翻译的文字,如果使用qm文件有对应的字符串,则使用对应的字符串进行替换,否则将显示sourceText参数指定的字符串。第二个参数是一个注释,用于解释前面的sourceText的含义,比如table一词既可以当做桌子翻译,又可以当成表格翻译,这时你就需要提供这个注释。或许你会问,使用翻译工具的时候不是有源代码吗?问题是,有可能人家不使用这个翻译工具,而使用别的工具,这样就不能保证会有这个源代码的预览;并且,你的程序不一定必须要发布源代码的;翻译人员往往只得到我们导出的ts文件,如果你加上注释,就可以方便翻译人员进行翻译。最后一个参数n用于指定字符串是否为复数。我们知道,很多语言,比如英语,很多名词的单复数形式是不相同的,为了解决这个问题,Qt在tr()函数中提供了一个参数n。
Returns a translated version of sourceText, optionally based on a disambiguation(消除歧义)string and value of n for strings containing plurals; otherwise returns sourceText itself if no appropriate translated string is available.
Example:
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
...
If the same sourceText is used in different roles within the same context, an additional identifying string may be passed in disambiguation (0 by default). In Qt 4.4 and earlier, this was the preferred way to pass comments to translators.
Example:
MyWindow::MyWindow()
{
QLabel *senderLabel = new QLabel(tr("Name:"));
QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
...
See Writing Source Code for Translation for a detailed description of Qt's translation mechanisms in general, and the Disambiguation section for information on disambiguation.
Warning: This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will probably result in crashes or other undesirable behavior.
tr()函数是QObject的函数,如果你的类不是继承自QObject,就不能直接使用tr()函数。比如我们在main()函数中希望增加一句设置MainWindow的title的代码:
w.setWindowTitle(tr("MyApp"));
直接这样写是无法通过编译的,因为main()函数是全局函数,所以这个tr()是找不到的。解决办法一是显式地调用QObject的函数:
w.setWindowTitle(QObject::tr("MyApp"));![](https://www.#.com/imgs/2/5/3/4/23/78e1e3a115342bc8b092d7d92afd6281.jpe)
或者,你可以使用QCoreApplication的translate()函数。你一定还记得,我们的main()函数的第一句总是QApplication app;,其实,QApplication就是QCoreApplication的子类。所以,我们也能这样去写:
w.setWindowTitle(app.translate("MyApp"));
由于在Qt程序中,QCoreApplication是一个单例类,因此,Qt提供了一个宏qApp,用于很方便的访问QCoreApplication的这个单例。所以,在其他文件中,我们也可以直接调用qApp.translate()来替换tr(),不过这并没有必要。
本文出自 “豆子空间” 博客,请务必保留此出处http://devbean.blog.51cto.com/448512/245063