QT Internationalization related classes (not previously seen codec->tounicode,qtextcodec,qlocale.tostring and Qlocale::setdefault,qinputmethod::locale ())

Source: Internet
Author: User
Tags locale setting


Qtextcodec provides a conversion between text encodings.

QT uses Unicode to store, draw, and manipulate strings. In many cases, you may want to manipulate different encoded data. For example, most Japanese documents are stored in Shift-jis or ISO 2022-jp, whereas the Russian user's documents are encoded in KOI8-R or Windows-1251.

QT provides a set of QTEXTCODEC classes for converting between non-Unicode and Unicode formats. You can also create your own codec.

The supported encodings are as follows:

· Apple Roman

· Big5

· Big5-hkscs

· CP949

· Euc-jp

· Euc-kr

· gb18030-0

· IBM 850

· IBM 866

· IBM 874

· ISO 2022-JP

· ISO 8859-1 to 10

· ISO 8859-13 to 16

· ISCII-BNG, Dev, GJR, Knd, MLM, Ori,pnj, TLG, and TML

· JIS X 0201

· JIS X 0208

· Koi8-r

· Koi8-u

· Shift-jis

· TIS-620

· Tscii

· UTF-8

· UTF-16

· Utf-16be

· Utf-16le

· UTF-32

· Utf-32be

· Utf-32le

· Windows-1250 to 1258

If you enable support for QT compilation with ICU, most of the codecs supported by the ICU are also available in the program.

Qtextcodecs can be used like the following. The native encoding is converted to Unicode, assuming there is a Russian koi8-r encoded string and wants to convert it to Unicode. The simple approach is to:

qbytearray encodedstring = "...";

qtextcodec*codec=qtextcodec:: Codecforname ("Koi8-r");

QString string = Codec->tounicode (encodedstring);

Thereafter, the text string is converted to Unicode. It is also simple to convert a Unicode string into a locally encoded string:

QString string = "...";
Qtextcodec qtextcodec:: Codecforname ("Koi8-r");
qbytearray encodedstring = Codec->fromunicode (string);

In order to read and write with different codes, Qtextstream and its function setcodec () can be used.

When trying to convert a block of data, there are some things to be aware of, such as when a block is received from the network, in which case multibyte characters may be divided into two blocks of data. It is best to simply cause the loss of the character, and the worst may cause the conversion to fail.

In this case, the method is to create a Qtextdecoder object for the decoder and use this Qtextdecoder object throughout the decoding process. Examples are as follows:

Qtextcodec qtextcodec:: Codecforname ("Shift-jis");
qtextdecoder*decoder = Codec->makedecoder ();
QString string;
while (New_data_available ()) {
qbytearray chunk = Get_new_data ();
string + = Decoder->tounicode (chunk);
Delete decoder;

The Qtextdecoder object maintains the state between data blocks, even if multibyte characters are divided into different chunks of data to work properly.

Creatingyour Own Codec Class

QT supports adding a new text encoding by creating a qtextcodec subclass.

Pure virtual functions describe the encoding to the system, and in the different text file formats supported by Qtextstream, this codec is required for input and output of X11 specific characters.

In order to add a new encoding to QT, inherit the Qtextcodec and re-implement the following functions:



name ()

Returns the official name for the encoding. If the encoding is listed in the IANA character-sets encoding file, the name should be the preferred MIME name fo R the encoding.

aliases ()

Returns A list of alternative names for the encoding. QTEXTCODEC provides a default implementation that returns an empty list. For example, the "Iso-8859-1" has "latin1", "CP819", "IBM819", and "iso-ir-100" as aliases.

Mibenum ()

Return the MIB enum for the encoding if it's listed in the IANA character-sets encoding file.

Converttounicode ()

Converts an 8-bit character string to Unicode.

Convertfromunicode ()

Converts a Unicode string to an 8-bit character string.

Member Type Documentationnumqtextcodec::conversionflag
Flags Qtextcodec::conversionflags




Qtextcodec::D efaultconversion


No flag is set.



IF This flag is set, each invalid input character is output as a null character.



Ignore any Unicode byte-order mark and don ' t generate.


Qtranslator provides support for internationalization of the output of text.

The Qtranslator object contains a set of translations from the source language to the target language. Qtranslator provides functions to find translations in a translation file. The translation file was created by Qt linguist.

The most common usage of qtranslator is to load a translator without seeing it, install it with Qcoreapplication::installtranslator (), and use it through QOBJECT::TR (). For example:

int Main (intargc,char*argv[])


qapplication app (argc, argv);

Qtranslator Translator;

Translator.load ("Hellotr_la");

App.installtranslator (&translator);

Qpushbutton Hello (qpushbutton:: tr ("Hello world!"));

Hello.resize (100,30);

Hello.show ();

return App.exec ();


Note: Translator must be created before the widgets of the program.

Most programs do not have to do other things with this class. Other functions provided by the Qtranslator class are useful for manipulating programs that translate files.

Lookingup Translations

You can find a translation by translate (). Translate () accepts three parameters:

· context – typically a class name that calls the TR () function

· Source Text – usually the TR () parameter.

· disambiguation – An optional string that eliminates the ambiguity of different usages of the same text in the same context.

For example, if the program is running in a Polish environment, the "Cancel" in the dialog box may change to "Anuluj".

The context is the dialog class name, which usually has no comment and the translated text is "Anuluj".

But it's not always that simple. The Spanish version of the print dialog set for duplex printing and binding may require "Activado" and "Activada" translated to "Enabled." 。 In this case, the source text is "Enabled" in all cases, the context is the dialog class name, but these two may disambiguate, one is "two-sided printing" and the other is "binding". Disambiguation allows translator to choose the right gender for the Spanish version, allowing Qt to differentiate between translations.

Usingmultiple Translations

More than one translation file can be used in a program, and the translation is found in the reverse order of installation, so the most recently installed translated files are first searched, and the earliest installed translation files are finally found. Once the translation is found with a matching string, the lookup is stopped.

This mechanism allows a particular translation to be selected or given precedence over other translations. Uninstalling the translator from the program requires only passing it to the Qcoreapplication::removetranslator () function and using Qcoreapplication::installtranslator (). Reinstall. It will be the first translation to be searched for a matching string.


In different languages, Qlocale provides conversions for numbers and their strings.

Qlocale is initialized by a language/country pair in the constructor, and provides a numeric-to-string and string-to-number conversion function. For example:

Qlocale Egyptian (qlocale:: Arabic,qlocale:: Egypt);

QString S1 = egyptian.tostring (1.571429E+07, ' e ');

QString s2 = egyptian.tostring (10);

Double d =egyptian.todouble (S1);

int i =egyptian.toint (S2);

Qlocale supports the concept of the default locale, which is determined by the system settings that the program starts. The default locale can be changed by the static function SetDefault (). Setting the default locale has the following effects:

· If a Qlocale object has a default constructor generated, the default locale setting is used.

· Functions such as Qstring::toint (), qstring::todouble () translate strings according to the default locale. If it fails, it returns to the "C" environment.

· Qstring::arg () uses the default locale to generate formatted numbers if the format string indicates a location that contains ' L ', such as '%L1 '

The following example shows how to use the Qlocale directly:

qlocale:: SetDefault (qlocale(qlocaleqlocale:: Israel));
Qlocale //Constructs a default Qlocale
QString S1 = hebrew.tostring (15714.3, ' e ');
bool OK;
Double D;
qlocale:: SetDefault (qlocale:: C);
QString //OK = = False
QString //OK = = true, D = = 1234.56
qlocale:: SetDefault (qlocale:: German);
QString //OK = = true, D = = 1234.56
QString //OK = = true, D = = 1234.56
qlocale:: SetDefault (qlocale(qlocaleqlocale:: unitedstates));
QString ("%1%l2%l3")
. Arg (12345). Arg (12345). Arg (12345,0,16);
str = = "12345 12,345 3039"

If you specify a language/country in the constructor, one of the following three things can happen:

· If the language/country is found in the database, use it.

· If the language can be found, but the country is not found or the country is other countries, then the language will be used in conjunction with the most appropriate country.

If the language and country are not found, then Qlocale is the default locale.

You can use language () and country () to determine the language and country you are actually using.

Another way to construct a Qlocale object is to specify the locale name.

qlocale Korean ("Ko");
Qlocale Swiss ("De_ch");

constructor to convert the locale name to language/country. It not only uses the system language environment database.

Note: For the current keyboard input area, check Qinputmethod::locale ().


QT Internationalization related classes (not previously seen codec->tounicode,qtextcodec,qlocale.tostring and Qlocale::setdefault,qinputmethod::locale ())

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.