KDE 4.5 PyKDE API Reference

- KDE's Python API

# KLocalizedString Class Reference

`from PyKDE4.kdecore import *`

## Detailed Description

Class for producing and handling localized messages

KLocalizedString handles translation and specific needs of argument substitution and formatting in localized message strings.

Topics: - gen_usage - spec_usage - subs_notes - other_ref

General Usage

This class should mostly not be used directly, but through wrapper i18n calls which return QString, for localization of user visible messages in applications.

For the most frequent message type, the one without any arguments, you would use simply:

       QString msg = i18n("Just plain info");

If there are arguments to be substitued into the message, you just add them after the message string:

       QString msg = i18n("%1 has scored %2", playerName, score);

There can be up to some final number of arguments added like this (i18n is realized by overloaded templates). If you overrun this number, use ki18n* series of calls (described below). You can use several types as arguments, see subs methods.

Sometimes a short message can be ambiguous in English, then you would use the context version, i18nc. There the first string is context, and the second is the message which really gets displayed:

       QString msg = i18nc("Player name - score", "%1 - %2", playerName, score);

While English diferentiates plural forms only between 1 and else, in other languages it might not be that simple, or it might be simpler. To handle this properly, use plural call, i18np:

       QString msg = i18np("One image in album %2", "%1 images in album %2",
                           numImages, albumName);

Note that the plural form shall be decided by first integer-valued argument, (numImages in the example above). In rare cases when there are two integer arguments, you should take care to order them properly.

Finally, message might need both context and plural, which is provided by i18ncp call:

       QString msg = i18ncp("Personal file", "One file", "%1 files", numFiles);

Be carefull not to use literal string as first argument after message text in basic i18n() call. In debug mode, it will even trigger the static assert, giving error at compile time. This is in order to prevent misnamed calls: it may happen that you add context or plural to previously basic message, but forget to change the name of the call.

All message strings are expected to pass for well-formed XML, whether or not the output device supports some form of markup. Thus, predefined XML entities are always available: &amp;lt;, &amp;gt;, &amp;amp;, &amp;apos;, and &amp;quot;. E.g. if you need a non-tag less-than sign, use &amp;lt; entity instead. The exception to the well-formed XML requirement is the ampersand (&amp;), which is used a lot for marking accelerators, so you should not write it as &amp;amp; (except in the very unlikely case when the construct with the naked ampersand can be interpreted as an entity in itself).

Specialized Usage

There are some situations where i18n* calls are not sufficient or convenient. For one, if you need to substitute many arguments. Or, if you find that you need to defer the substitution. For this you can use the ki18n call which returns a KLocalizedString, substitute arguments using its subs methods, and finalize the translation by calling its toString method. For example:

       KLocalizedString ks;
       case (reportSource) {
         SRC_ENG: ks = ki18n("Engineering reports: %1"); break;
         SRC_HEL: ks = ki18n("Helm reports: %1"); break;
         SRC_SON: ks = ki18n("Sonar reports: %1"); break;
         default: ks = ki18n("General report: %1");
       }
       QString msg = ks.subs(reportText).toString();

Another case is when you want extra formatting of arguments, like field width or number of decimals. subs methods can take these formatting parameters. In particular, you should never use some custom way to format arguments, as subs methods will also properly localize them:

       QString s = i18n("Rounds: %1", myNumberFormat(n, 8)); // bad, number not localized
       QString s = ki18n("Rounds: %1").subs(n, 8).toString(); // good, number localized

There are also context, plural and context-plural variants:

       QString s = ki18nc("No function", "None").toString();
       QString s = ki18np("File found", "%1 files found").subs(n).toString();
       QString s = ki18ncp("Personal file", "One file", "%1 files").subs(n).toString();

If you need translation using locale (ie. KLocale object) other than the default, you can use overloaded toString method which takes pointer to a locale:

       KLocale *myLocale;
       ...
       QString msg = ki18n("Welcome").toString(myLocale);

Normally all loaded catalogs are searched for translation, and the first found translation is returned. Sometimes this may lead to clashes, especially when dealing with specialized collection catalogs (country names, language names, etc.) in which messages are not equipped with contexts. In such situations, toString method can take the name of the specific catalog in which to look for translation:

       QString trName = ki18n("Georgia").toString("countries");

Translators have a capability to script translations at runtime, which is for the most part transparent to the programmer. However, sometimes the programmer may help by providing some dynamic context to the message, using the inContext method of KLocalizedString. Unlike the ordinary context, this one changes at runtime; translators have the means to fetch it and use it to script the translation properly. An example:

       KLocalizedString ks = ki18nc("%1 is user name; may have "
                                    "dynamic context gender=[male,female]",
                                    "%1 went offline");
       if (knownUsers.contains(user) && !knownUsers[user].gender.isEmpty()) {
         ks = ks.inContext("gender", knownUsers[user].gender);
       }
       QString msg = ks.subs(user).toString();

Several dynamic contexts, with different keys, can be added like this.

Placeholder Substitution

Hopefully, for the most part placeholders are being substituted the way you would intuitively expect them to be. Nevertheless:

- Placeholders are substituted in one pass, so no need to worry about
argument itself containing a placeholder.

- All same-numbered placeholders are substituted with same argument.

- Placeholders directly index arguments: they should be numbered from 1
upwards, without gaps in the sequence so that each argument is indexed. Otherwise you will get error marks in messages at runtime (when compiled in debug mode), and any invalid placeholder will be left unsubstituted. The exception is plural-deciding argument in plural call, where it is allowed to drop its placeholder in either singular or plural form.

- If none of the arguments supplied to a plural call is integer-valued,
you will get an error mark in message at runtime (in debug mode).

- Plain number arguments will be normally formatted as if they denote
amounts, according to language rules (thousands separation, etc.) But sometimes a number is a numerical identifier (e.g. port number), and to be treated as such, wrap the placeholder with the numid tag:

           QString msg = i18n("Using port <numid>%1</numid>", port);

Further References

KDE Techbase contains a series of tutorials on preparing the code for localization (and on internationalization process in general), where the intended patterns of usage of i18n API are covered in great detail.

All i18n'd messages, whether sent to widgets expecting plain text or allowing Qt rich text (HTML), support the new KDE semantic markup for user interface text, KUIT in short. Semantic markup both increases the consistency of visual presentation for the end user, and provides extra information to translators, so that translations can be of higher quality. KUIT is documented in an Techbase article as well.

See also:
  KLocale

Author:
  Chusslove Illich <caslav.ilic@gmx.net>

## Methods
| __init__ (self)
| __init__ (self, KLocalizedString rhs)
| __init__ (self, QString ctxt, QString msg, QString plural)
KLocalizedString | inContext (self, QString key, QString text)
bool | isEmpty (self)
KLocalizedString | subs (self, long a, int fieldWidth=0, int base=10, QChar fillChar=QLatin1Char(' '))
KLocalizedString | subs (self, QChar a, int fieldWidth=0, QChar fillChar=QLatin1Char(' '))
KLocalizedString | subs (self, QString a, int fieldWidth=0, QChar fillChar=QLatin1Char(' '))
QString | toString (self)
QString | toString (self, KLocale locale)
QString | toString (self, QString catalogName)
QString | toString (self, KLocale locale, QString catalogName)

## Method Documentation

__init__ | ( |  | self ) |

Constructs an empty message, which is not valid for finalization. Useful when you later need to assign KLocalizedString obtained by one of ki18n* calls.

See also:
  isEmpty()

__init__ | ( | self, |
|  | KLocalizedString | rhs
| ) |  |  |

Copy constructor.

__init__ | ( | self, |
|  | QString | ctxt,
|  | QString | msg,
|  | QString | plural
| ) |  |  |

KLocalizedString inContext | ( | self, |
|  | QString | key,
|  | QString | text
| ) |  |  |

Adds dynamic context to the message.

Parameters:

  | key | context key
  | text | context value

Returns:
  resultant KLocalizedString

bool isEmpty | ( |  | self ) |

Checks whether the message is empty. This will happen if you just constructed the object via default constructor.

Empty messages are not valid for finalization; if you use toString() on them, you will get error mark instead of empty QString (in debug mode).

Returns:
  true if the message is empty, else false

KLocalizedString subs | ( | self, |
|  | long | a,
|  | int | fieldWidth=0,
|  | int | base=10,
|  | QChar | fillChar=QLatin1Char(' ')
| ) |  |  |

Substitutes a QString argument into the message.

Parameters:

  | a | the argument
  | fieldWidth | width of the formatted field, padded by spaces. Positive value aligns right, negative aligns left
  | fillChar | the character used to fill up the empty places when field width is greater than argument width

Returns:
  resultant KLocalizedString

KLocalizedString subs | ( | self, |
|  | QChar | a,
|  | int | fieldWidth=0,
|  | QChar | fillChar=QLatin1Char(' ')
| ) |  |  |

Substitutes a QString argument into the message.

Parameters:

  | a | the argument
  | fieldWidth | width of the formatted field, padded by spaces. Positive value aligns right, negative aligns left
  | fillChar | the character used to fill up the empty places when field width is greater than argument width

Returns:
  resultant KLocalizedString

KLocalizedString subs | ( | self, |
|  | QString | a,
|  | int | fieldWidth=0,
|  | QChar | fillChar=QLatin1Char(' ')
| ) |  |  |

Substitutes a QString argument into the message.

Parameters:

  | a | the argument
  | fieldWidth | width of the formatted field, padded by spaces. Positive value aligns right, negative aligns left
  | fillChar | the character used to fill up the empty places when field width is greater than argument width

Returns:
  resultant KLocalizedString

QString toString | ( |  | self ) |

Since:
  4.5

Like toString, but looks for translation only in specific catalog.

Parameters:

  | locale | locale from which translations are to be taken
  | catalogName | the name of the catalog to check for translation

Returns:
  finalized translation

QString toString | ( | self, |
|  | KLocale | locale
| ) |  |  |

Since:
  4.5

Like toString, but looks for translation only in specific catalog.

Parameters:

  | locale | locale from which translations are to be taken
  | catalogName | the name of the catalog to check for translation

Returns:
  finalized translation

QString toString | ( | self, |
|  | QString | catalogName
| ) |  |  |

Since:
  4.5

Like toString, but looks for translation only in specific catalog.

Parameters:

  | locale | locale from which translations are to be taken
  | catalogName | the name of the catalog to check for translation

Returns:
  finalized translation

QString toString | ( | self, |
|  | KLocale | locale,
|  | QString | catalogName
| ) |  |  |

Since:
  4.5

Like toString, but looks for translation only in specific catalog.

Parameters:

  | locale | locale from which translations are to be taken
  | catalogName | the name of the catalog to check for translation

Returns:
  finalized translation