[Development] QT_NO_CAST_FROM_ASCII for platformsupport

Olivier Goffart olivier at woboq.com
Tue Feb 14 15:03:34 CET 2012


On Tuesday 14 February 2012 13:50:06 Johannes Zellner wrote:
> Hi,
> 
> what is the reason for " DEFINES += QT_NO_CAST_FROM_ASCII "
> in the platformsupport.pro file?
> 
> I just hit that and would like to understand why we have this
> inconvenience here.

Ok, i don't know the specific on why it is there in platform support. The rest 
of Qt just has QT_ASCII_CAST_WARNINGS

Anyway, casting from char* to QString must be avoided on library code.

the reason:

if you have

QString foo = file.readAll();

This compile fine, and even look right, but might be wrong.
because a char* do not say anything about the encoding. Is it latin1, utf8, 
other?

So Qt provide QTextCodec::codecForCString.
This one will be set by the application author, if he want to have the 
convinience of writing that code, and he knows that all the time he does that 
it is with the right encoding.

There is also QTextCodec::codecForLocale used by QString::fromLocal8Bit.

For example, in a french programing team, you would have
label->setText("Résultats Erronés");
And this will probably be in latin1, because the file is saved as such on the 
disc. (and latin1 is faster than utf8).
But a russian team will have
label->setText("Ошибочные результаты");
And the source code will be in their russian encoding.
Another (more modern) team would work with utf8.

So if in your library you do
QString foo = file.readAll();
The result will depends on the application.


So the rule is:
 - Always be explicit about which encoding you import the string from.
 - If it is a literal, use QStringLiteral in 95% of the case, and 
QLatin1String in most of th	e other cases.






More information about the Development mailing list