Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# QTextCodec Class Reference

The QTextCodec class provides conversions between text encodings. More...

    #include <QTextCodec>

Inherited by QTsciiCodec, QGbkCodec, QGb2312Codec, and QBig5hkscsCodec.

Note: All the functions in this class are reentrant, except setCodecForTr(), setCodecForCStrings(), QTextCodec(), and ~QTextCodec().

- List of all members, including inherited members
- Compatibility members

### Public Types

- class ConverterState
- enum ConversionFlag { DefaultConversion, ConvertInvalidToNull, KeepHeader, WriteHeader }
- typedef ConversionFlags

### Public Functions

- virtual QList<QByteArray> aliases () const
- bool canEncode ( QChar ch ) const
- bool canEncode ( const QString & s ) const
- QByteArray fromUnicode ( const QString & str ) const
- QByteArray fromUnicode ( const QChar * in, int length, ConverterState * state = 0 ) const
- QTextDecoder * makeDecoder () const
- QTextEncoder * makeEncoder () const
- virtual int mibEnum () const = 0
- virtual QByteArray name () const = 0
- QString toUnicode ( const QByteArray & a ) const
- QString toUnicode ( const char * in, int length, ConverterState * state = 0 ) const
- QString toUnicode ( const char * chars ) const

### Static Public Members

- QList<QByteArray> availableCodecs ()
- QList<int> availableMibs ()
- QTextCodec * codecForCStrings ()
- QTextCodec * codecForLocale ()
- QTextCodec * codecForMib ( int mib )
- QTextCodec * codecForName ( const QByteArray & name )
- QTextCodec * codecForName ( const char * name )
- QTextCodec * codecForTr ()
- void setCodecForCStrings ( QTextCodec * c )
- void setCodecForLocale ( QTextCodec * c )
- void setCodecForTr ( QTextCodec * c )

### Protected Functions

- QTextCodec ()
- virtual ~QTextCodec ()
- virtual QByteArray convertFromUnicode ( const QChar * in, int length, ConverterState * state ) const = 0
- virtual QString convertToUnicode ( const char * chars, int len, ConverterState * state ) const = 0

## Detailed Description

The QTextCodec class provides conversions between text encodings.

Qt uses Unicode to store, draw and manipulate strings. In many situations you may wish to deal with data that uses a different encoding. For example, most Japanese documents are still stored in Shift-JIS or ISO2022, while Russian users often have their documents in KOI8-R or CP1251.

Qt provides a set of QTextCodec classes to help with converting non-Unicode formats to and from Unicode. You can also create your own codec classes (see later).

The supported encodings are:

- Latin1
- Big5 -- Chinese
- Big5-HKSCS -- Chinese
- eucJP -- Japanese
- eucKR -- Korean
- GB2312 -- Chinese
- GBK -- Chinese
- GB18030 -- Chinese
- JIS7 -- Japanese
- Shift-JIS -- Japanese
- TSCII -- Tamil
- utf8 -- Unicode, 8-bit
- utf16 -- Unicode
- KOI8-R -- Russian
- KOI8-U -- Ukrainian
- ISO8859-1 -- Western
- ISO8859-2 -- Central European
- ISO8859-3 -- Central European
- ISO8859-4 -- Baltic
- ISO8859-5 -- Cyrillic
- ISO8859-6 -- Arabic
- ISO8859-7 -- Greek
- ISO8859-8 -- Hebrew, visually ordered
- ISO8859-8-i -- Hebrew, logically ordered
- ISO8859-9 -- Turkish
- ISO8859-10
- ISO8859-13
- ISO8859-14
- ISO8859-15 -- Western
- IBM 850
- IBM 866
- CP874
- CP1250 -- Central European
- CP1251 -- Cyrillic
- CP1252 -- Western
- CP1253 -- Greek
- CP1254 -- Turkish
- CP1255 -- Hebrew
- CP1256 -- Arabic
- CP1257 -- Baltic
- CP1258
- Apple Roman
- TIS-620 -- Thai

QTextCodecs can be used as follows to convert some locally encoded string to Unicode. Suppose you have some string encoded in Russian KOI8-R encoding, and want to convert it to Unicode. The simple way to do it is like this:

        QByteArray locallyEncoded = "..."; // text to convert
        QTextCodec *codec = QTextCodec::codecForName("KOI8-R"); // get the codec for KOI8-R
        QString unicodeString = codec->toUnicode(locallyEncoded);

After this, `unicodeString` holds the text converted to Unicode. Converting a string from Unicode to the local encoding is just as easy:

        QString unicodeString = "..."; // any Unicode text
        QTextCodec *codec = QTextCodec::codecForName("KOI8-R"); // get the codec for KOI8-R
        QByteArray locallyEncoded = codec->fromUnicode(unicodeString);

Some care must be taken when trying to convert the data in chunks, for example, when receiving it over a network. In such cases it is possible that a multi-byte character will be split over two chunks. At best this might result in the loss of a character and at worst cause the entire conversion to fail.

The approach to use in these situations is to create a QTextDecoder object for the codec and use this QTextDecoder for the whole decoding process, as shown below:

        QTextCodec *codec = QTextCodec::codecForName("Shift-JIS");
        QTextDecoder *decoder = codec->makeDecoder();

        QString unicodeString;
        while(receiving_data) {
            QByteArray chunk = new_data;
            unicodeString += decoder->toUnicode(chunk.data(), chunk.length());
        }

The QTextDecoder object maintains state between chunks and therefore works correctly even if a multi-byte character is split between chunks.

### Creating your own Codec class

Support for new text encodings can be added to Qt by creating QTextCodec subclasses.

You may find it more convenient to make your codec class available as a plugin; see the plugin documentation for more details.

The abstract virtual functions describe the encoder to the system and the coder is used as required in the different text file formats supported by QTextStream, and under X11, for the locale-specific character input and output.

To add support for another encoding to Qt, make a subclass of QTextCodec and implement at least the following methods:

        QByteArray name() const

Return 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 for the encoding.

        int mibEnum() const

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

        QString convertToUnicode(const char* chars, int len, ConverterState *state) const

Converts len characters from chars to Unicode. The ConverterState structure contains some conversion flags and is used by the QTextDecoder to keep state. Some methods call the method with a 0 state pointer.

        QByteArray convertFromUnicode(const QChar *uc, int len, ConverterState *state) const

Converts len characters (of type QChar) from the start of the array uc, returning a QByteArray result. ConverterState structure contains some conversion flags and is used by the QTextEncoder to keep state. Some methods call the method with a 0 state pointer.

        QList<QByteArray> aliases() const

This method can be reimplemented if your codec is known by several names. The codec for "ISO-8859-1" does for example return (amongst others) "latin1", "US_ASCII" and "iso-ir-100" as aliases.

Codecs can also be created as plugins.

## Member Type Documentation

### enum QTextCodec::ConversionFlag
typedef QTextCodec::ConversionFlags

The ConversionFlags typedef can store a combination of ConversionFlag values.

## Member Function Documentation

### QTextCodec::QTextCodec () `[protected]`

Constructs a QTextCodec, and gives it the highest precedence. The QTextCodec should always be constructed on the heap (i.e. with `new`). Qt takes ownership and will delete it when the application terminates.

Warning: This function is not reentrant.

### QTextCodec::~QTextCodec () `[virtual protected]`

Destroys the QTextCodec. Note that you should not delete codecs yourself: once created they become Qt's responsibility.

Warning: This function is not reentrant.

### QList<QByteArray> QTextCodec::aliases () const `[virtual]`

Subclasses can return a number of aliases for the codec in question.

Standard aliases for codecs can be found in the IANA character-sets encoding file.

### QList<QByteArray> QTextCodec::availableCodecs () `[static]`

### QList<int> QTextCodec::availableMibs () `[static]`

### bool QTextCodec::canEncode ( QChar ch ) const

Returns true if the Unicode character ch can be fully encoded with this codec; otherwise returns false.

### bool QTextCodec::canEncode ( const QString & s ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

s contains the string being tested for encode-ability.

### QTextCodec * QTextCodec::codecForCStrings () `[static]`

Returns the codec used by QString to convert to and from `const char*` and QByteArrays. If this function returns 0 (the default), QString assumes Latin1.

See also setCodecForCStrings().

### QTextCodec * QTextCodec::codecForLocale () `[static]`

Returns a pointer to the codec most suitable for this locale.

### QTextCodec * QTextCodec::codecForMib ( int mib ) `[static]`

Returns the QTextCodec which matches the MIBenum mib.

### QTextCodec * QTextCodec::codecForName ( const QByteArray & name ) `[static]`

Searches all installed QTextCodec objects and returns the one which best matches name; the match is case-insensitive. Returns 0 if no codec matching the name name could be found.

### QTextCodec * QTextCodec::codecForName ( const char * name ) `[static]`

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

### QTextCodec * QTextCodec::codecForTr () `[static]`

Returns the codec used by QObject::tr() on its argument. If this function returns 0 (the default), tr() assumes Latin1.

See also setCodecForTr().

### QByteArray QTextCodec::convertFromUnicode ( const QChar * in, int length, ConverterState * state ) const `[pure virtual protected]`

QTextCodec subclasses must reimplement this function.

It converts the first len characters of uc from Unicode to the encoding of the subclass, producing a QByteArray.

state can be 0 in which case the conversion is stateless and default conversion rules should be used. If state is not 0, the codec should save the state after the conversion in state, and adjust the remainingChars and invalidChars members of the struct.

### QString QTextCodec::convertToUnicode ( const char * chars, int len, ConverterState * state ) const `[pure virtual protected]`

QTextCodec subclasses must reimplement this function.

It converts the first len characters of chars from the encoding of the subclass to Unicode, producing a QString.

state can be 0 in which case the conversion is stateless and default conversion rules should be used. If state is not 0, the codec should save the state after the conversion in state, and adjust the remainingChars and invalidChars members of the struct.

### QByteArray QTextCodec::fromUnicode ( const QString & str ) const

Converts str from Unicode to the encoding of this codec, producing a QByteArray.

### QByteArray QTextCodec::fromUnicode ( const QChar * in, int length, ConverterState * state = 0 ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

### QTextDecoder * QTextCodec::makeDecoder () const

Creates a QTextDecoder which stores enough state to decode chunks of char* data to create chunks of Unicode data.

The caller is responsible for deleting the returned object.

### QTextEncoder * QTextCodec::makeEncoder () const

Creates a QTextEncoder which stores enough state to encode chunks of Unicode data as char* data.

The caller is responsible for deleting the returned object.

### int QTextCodec::mibEnum () const `[pure virtual]`

Subclasses of QTextCodec must reimplement this function. It returns the MIBenum (see the IANA character-sets encoding file for more information). It is important that each QTextCodec subclass returns the correct unique value for this function.

### QByteArray QTextCodec::name () const `[pure virtual]`

QTextCodec subclasses must reimplement this function. It returns the name of the encoding supported by the subclass.

If the codec is registered as a character set in the IANA character-sets encoding file this method should return the preferred mime name for the codec if defined, otherwise it's name.

### void QTextCodec::setCodecForCStrings ( QTextCodec * c ) `[static]`

Sets the codec used by QString to convert to and from `const char*` and QByteArrays. If c is 0 (the default), QString assumes Latin1.

Warning: Some codecs do not preserve the characters in the ASCII range (0x00 to 0x7f). For example, the Japanese Shift-JIS encoding maps the backslash character (0x5a) to the Yen character. This leads to unexpected results when using the backslash character to escape characters in strings used in e.g. regular expressions. Use QString::fromLatin1() to preserve characters in the ASCII range when needed.

Warning: This function is not reentrant.

See also codecForCStrings(), setCodecForTr(), and setCodecForCStrings().

### void QTextCodec::setCodecForLocale ( QTextCodec * c ) `[static]`

Set the codec to c; this will be returned by codecForLocale(). This might be needed for some applications that want to use their own mechanism for setting the locale.

See also codecForLocale().

### void QTextCodec::setCodecForTr ( QTextCodec * c ) `[static]`

Sets the codec used by QObject::tr() on its argument to c. If c is 0 (the default), tr() assumes Latin1.

If the literal quoted text in the program is not in the Latin1 encoding, this function can be used to set the appropriate encoding. For example, software developed by Korean programmers might use eucKR for all the text in the program, in which case the main() function might look like this:

        int main(int argc, char** argv)
        {
            QApplication app(argc, argv);
            ... install any additional codecs ...
            QTextCodec::setCodecForTr(QTextCodec::codecForName("eucKR"));
            ...
        }

Note that this is not the way to select the encoding that the user has chosen. For example, to convert an application containing literal English strings to Korean, all that is needed is for the English strings to be passed through tr() and for translation files to be loaded. For details of internationalization, see the Qt internationalization documentation.

Warning: This function is not reentrant.

See also codecForTr(), setCodecForTr(), and setCodecForCStrings().

### QString QTextCodec::toUnicode ( const QByteArray & a ) const

Converts a from the encoding of this codec t Unicode, producing a QString.

### QString QTextCodec::toUnicode ( const char * in, int length, ConverterState * state = 0 ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

### QString QTextCodec::toUnicode ( const char * chars ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

chars contains the source characters.