Non-ascii-characters-in-Qt-source-files
Article Metadata
Sometimes non-ASCII strings need to be displayed in Qt applications, most commonly in cases where the application is in a language that has an alphabet not covered with plain ASCII. Occasionally it seems the simplest solution is just to insert those strings in their native form in the sources - this is unfortunately rarely a good solution. While the strings might look correct in an editor, the compiler and target platform might interpret them differently. The recommendation is thus to *always* avoid putting non-ASCII string is the sources. The basic use-cases can be covered with two methods:
1. Qt's translation mechanism
To be used if the strings are known in advance. While it might appear complex a first glance, it is very well suited to translating applications. Here's an example how to use this mechanism:
//: This name refers to a host name.
hostNameLabel->setText(tr("Name:"));
/*: This text refers to a C++ code example. */
QString example = tr("Example");
That is all that need to be done with the actual strings. For a more detailed introduction (how to compile language files, how to choose the translation language, etc) see http://doc.trolltech.com/4.7/i18n-source-translation.html
Note that some of the tooling creates code with translation already in mind - QtDesigner for example always puts in the tr() function calls automatically, making QWidget, menu and other element translation easy.
2. On-the-fly conversion
The first method is good as long as you know the strings in advance - sometimes these will be generated by 3rd party servers, contained in plaintext datafiles or similar. In that case the translation engine is of limited use, but Qt has a solution for that case too - it can read and write files through predefined codec filters in a very simple manner:
QTextStream out(&file);
out.setCodec("UTF-8");
( the list of available codecs is at http://doc.trolltech.com/4.7/qtextcodec.html#details )
In either case, the important thing to remember is to avoid non-ASCII chars in source files and non-UTF encodings for strings within Qt.


(no comments yet)