Writing cross-platform international software with Qt is a gentle, incremental process. Your software can become internationalized in the stages described in the following sections. For more information about internalizing Qt Quick application, see Qt Quick 的国际化和本地化 .
由于
QString
uses the Unicode encoding internally, every language in the world can be processed transparently using familiar text processing operations. Also, since all Qt functions that present text to the user take a
QString
as a parameter, there is no
char *
to
QString
conversion overhead.
Strings that are in "programmer space" (such as
QObject
names and file format texts) need not use
QString
; the traditional
char *
或
QByteArray
class will suffice.
You're unlikely to notice that you are using Unicode;
QString
,和
QChar
are just easier versions of the crude
const char *
and
char
from traditional C.
char *
strings in source code are assumed to be
UTF-8
encoded when being implicitly converted to a
QString
. If your C string literal uses a different encoding, use
QString::fromLatin1
() 或
QTextCodec
to convert the literal to a Unicode encoded
QString
.
Wherever your program uses a string literal (quoted text) that will be presented to the user, ensure that it is processed by the QCoreApplication::translate () function. Essentially all that is necessary to achieve this is to use the tr() function to obtain translated text for your classes, typically for display purposes. This function is also used to indicate which text strings in an application are translatable.
例如,假定
LoginWidget
是子类化的
QWidget
:
LoginWidget::LoginWidget() { QLabel *label = new QLabel(tr("Password:")); ... }
This accounts for 99% of the user-visible strings you're likely to write.
若引号文本不在成员函数中对于 QObject subclass, use either the tr() function of an appropriate class, or the QCoreApplication::translate () 函数直接:
void some_global_function(LoginWidget *logwid) { QLabel *label = new QLabel( LoginWidget::tr("Password:"), logwid); } void same_global_function(LoginWidget *logwid) { QLabel *label = new QLabel( QCoreApplication::translate("LoginWidget", "Password:"), logwid); }
Qt indexes each translatable string by the translation context it is associated with; this is generally the name of the QObject subclass it is used in.
Translation contexts are defined for new QObject -based classes by the use of the Q_OBJECT macro in each new class definition.
When tr() is called, it looks up the translatable string using a QTranslator object. For translation to work, one or more of these must have been installed on the application object in the way described in 启用翻译 .
Translating strings in QML works exactly the same way as in C++, with the only difference being that you need to call qsTr() instead of tr() . See also the page on Qt Quick 的国际化和本地化 .
The translation context for QObject and each QObject subclass is the class name itself. Developers subclassing QObject must use the Q_OBJECT macro in their class definition to override the translation context. This macro sets the context to the name of the subclass.
For example, the following class definition includes the
Q_OBJECT
macro, implementing a new tr() that uses the
MainWindow
上下文:
class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); ...
若
Q_OBJECT
is not used in a class definition, the context will be inherited from the base class. For example, since all
QObject
-based classes in Qt provide a context, a new
QWidget
subclass defined without a
Q_OBJECT
macro will use the
QWidget
context if its tr() function is invoked.
The following example shows how a translation is obtained for the class shown in the previous section:
void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); ...
Here, the translation context is
MainWindow
because it is the
MainWindow::tr()
function that is invoked. The text returned by the tr() function is a translation of "&File" obtained from the
MainWindow
上下文。
When Qt's translation tool, lupdate , is used to process a set of source files, the text wrapped in tr() calls is stored in a section of the translation file that corresponds to its translation context.
In some situations, it is useful to give a translation context explicitly by fully qualifying the call to tr(); for example:
QString text = QScrollBar::tr("Page up");
This call obtains the translated text for "Page up" from the
QScrollBar
context. Developers can also use the
QCoreApplication::translate
() function to obtain a translation for a particular translation context.
You can localize numbers by using appropriate tr() strings:
void Clock::setTime(const QTime &time) { if (tr("AMPM") == "AMPM") { // 12-hour clock } else { // 24-hour clock } }
In the example, for the US we would leave the translation of "AMPM" as it is and thereby use the 12-hour clock branch; but in Europe we would translate it as something else to make the code use the 24-hour clock branch.
It is sometimes necessary to provide internationalization support for strings used in classes that do not inherit
QObject
或使用
Q_OBJECT
macro to enable translation features. Since Qt translates strings at run-time based on the class they are associated with and
lupdate
looks for translatable strings in the source code, non-Qt classes must use mechanisms that also provide this information.
One way to do this is to add translation support to a non-Qt class using the Q_DECLARE_TR_FUNCTIONS () macro; for example:
class MyClass { Q_DECLARE_TR_FUNCTIONS(MyClass) public: MyClass(); ... };
This provides the class with
tr()
functions that can be used to translate strings associated with the class, and makes it possible for
lupdate
to find translatable strings in the source code.
另外,
QCoreApplication::translate
() function can be called with a specific context, and this will be recognized by
lupdate
and Qt Linguist.
Developers can include information about each translatable string to help translators with the translation process. These are extracted when
lupdate
is used to process the source files. The recommended way to add comments is to annotate the tr() calls in your code with comments of the form:
//: ...
or
/*
: ...
*/
范例:
//: This name refers to a host name. hostNameLabel->setText(tr("Name:")); /*: This text refers to a C++ code example. */ QString example = tr("Example");
In these examples, the comments will be associated with the strings passed to tr() in the context of each call.
Additional data can be attached to each translatable message. These are extracted when
lupdate
is used to process the source files. The recommended way to add meta-data is to annotate the tr() calls in your code with comments of the form:
//= <id>
This can be used to give the message a unique identifier to support tools which need it.
An alternative way to attach meta-data is to use the following syntax:
//~ <field name> <field contents>
This can be used to attach meta-data to the message. The field name should consist of a domain prefix (possibly the conventional file extension of the file format the field is inspired by), a hyphen and the actual field name in underscore-delimited notation. For storage in TS files, the field name together with the prefix "extra-" will form an XML element name. The field contents will be XML-escaped, but otherwise appear verbatim as the element's contents. Any number of unique fields can be added to each message.
范例:
//: This is a comment for the translator. //= qtn_foo_bar //~ loc-layout_id foo_dialog //~ loc-blank False //~ magic-stuff This might mean something magic. QString text = MyMagicClass::tr("Sim sala bim.");
You can use the keyword TRANSLATOR for translator comments. Meta-data appearing right in front of the TRANSLATOR keyword applies to the whole TS file.
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.
范例:
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.
Some translatable strings contain placeholders for integer values and need to be translated differently depending on the values in use.
To help with this problem, developers pass an additional integer argument to the tr() function, and typically use a special notation for plurals in each translatable string.
If this argument is equal or greater than zero, all occurrences of
%n
in the resulting string are replaced with a decimal representation of the value supplied. In addition, the translation used will adapt to the value according to the rules for each language.
范例:
int n = messages.count(); showMessage(tr("%n message(s) saved", "", n));
The table below shows what string is returned depending on the active translation:
Active Translation | |||
---|---|---|---|
n | 不翻译 | 法语 | English |
0 | "0 message(s) saved" | "0 message sauvegardé" | "0 message s saved" |
1 | "1 message(s) saved" | "1 message sauvegardé" | "1 message saved" |
2 | "2 message(s) saved" | "2 message s sauvegardé s " | "2 message s saved" |
37 | "37 message(s) saved" | "37 message s sauvegardé s " | "37 message s saved" |
This idiom is more flexible than the traditional approach; e.g.,
n == 1 ? tr("%n message saved") : tr("%n messages saved")
because it also works with target languages that have several plural forms (e.g., Irish has a special "dual" form that should be used when
n
is 2), and it handles the
n
== 0 case correctly for languages such as French that require the singular.
To handle plural forms in the native language, you need to load a translation file for this language, too. The lupdate tool has the
-pluralonly
command line option, which allows the creation of TS files containing only entries with plural forms.
见 Qt 季刊 Article Plural Forms in Translations for further details on this issue.
Instead of
%n
, you can use
%Ln
以产生本地化表示
n
. The conversion uses the default locale, set using
QLocale::setDefault
(). (If no default locale was specified, the system wide locale is used.)
A summary of the rules used to translate strings containing plurals can be found in the 复数翻译规则 文档。
若引号文本不在成员函数中对于 QObject subclass, use either the tr() function of an appropriate class, or the QCoreApplication::translate () 函数直接:
void some_global_function(LoginWidget *logwid) { QLabel *label = new QLabel( LoginWidget::tr("Password:"), logwid); } void same_global_function(LoginWidget *logwid) { QLabel *label = new QLabel( QCoreApplication::translate("LoginWidget", "Password:"), logwid); }
If you need to have translatable text completely outside a function, there are two macros to help:
QT_TR_NOOP
() 和
QT_TRANSLATE_NOOP
(). They merely mark the text for extraction by the
lupdate
tool. The macros expand to just the text (without the context).
Example of QT_TR_NOOP ():
QString FriendlyConversation::greeting(int type) { static const char *greeting_strings[] = { QT_TR_NOOP("Hello"), QT_TR_NOOP("Goodbye") }; return tr(greeting_strings[type]); }
Example of QT_TRANSLATE_NOOP ():
static const char *greeting_strings[] = { QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"), QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye") }; QString FriendlyConversation::greeting(int type) { return tr(greeting_strings[type]); } QString global_greeting(int type) { return QCoreApplication::translate("FriendlyConversation", greeting_strings[type]); }
若禁用
const char *
to
QString
automatic conversion by compiling your software with the macro
QT_NO_CAST_FROM_ASCII
defined, you'll be very likely to catch any strings you are missing. See
QString::fromUtf8
() 和
QString::fromLatin1
() 了解更多信息。
Accelerator values such as Ctrl+Q or Alt+F need to be translated too. If you hardcode
Qt::CTRL + Qt::Key_Q
for "quit" in your application, translators won't be able to override it. The correct idiom is:
exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcuts(QKeySequence::Quit);
The QString::arg () functions offer a simple means for substituting arguments:
void FileCopier::showProgress(int done, int total, const QString ¤tFile) { label.setText(tr("%1 of %2 files copied.\nCopying: %3") .arg(done) .arg(total) .arg(currentFile)); }
In some languages the order of arguments may need to change, and this can easily be achieved by changing the order of the % arguments. For example:
QString s1 = "%1 of %2 files copied. Copying: %3"; QString s2 = "Kopierer nu %3. Av totalt %2 filer er %1 kopiert."; qDebug() << s1.arg(5).arg(10).arg("somefile.txt"); qDebug() << s2.arg(5).arg(10).arg("somefile.txt");
produces the correct output in English and Norwegian:
5 of 10 files copied. Copying: somefile.txt Kopierer nu somefile.txt. Av totalt 10 filer er 5 kopiert.
Qt Linguist 手册 , Hello tr () 范例, 复数翻译规则
Qt 国际化 复数翻译规则