Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Non-ascii-characters-in-Qt-source-files

From Wiki
Jump to: navigation, search
Article Metadata
Compatibility
Platform(s):
Symbian
Article
Created: achipa (31 Dec 2010)
Last edited: hamishwillee (24 Jul 2012)

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.

This page was last modified on 24 July 2012, at 02:04.
32 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×