For those who use Qt with QT_NO_CAST_FROM_ASCII
enabled char*
s and std::strings
cannot be assigned to a QString
or cast to a QString
.
This will not compile with QT_NO_CAST_FROM_ASCII
enabled:
QString foo( "Hello World" );
You could do this but Qt frowns upon it because it creates, "temporary QString
objects and make a deep copy of the character data":
QString foo( QString::fromLatin1( "Hello World" ) );
Instead you have to use:
QString foo( QLatin1String( "Hello World" ) );
It's a little more frustrating if you need to get a QString
from a std::string
because you have to now call:
QString foo( QLatin1String( helloWorld.c_str() ) );
There is a direct conversion but not with Qt's recommended wrappers:
QString foo( QString::fromStdString( helloWorld ) );
That is to say I have not been able to find a wrapper for std::string
and JKSH asserts that there isn't one. So I believe that as of Qt 5.2 the preferred solution is to use the QLatin1String
wrapper.
(As an aside for those interested in multilingual software, Qt's QLatin1String
and QString::fromLaint1
both expect the char*
to be in proper unicode; QString::fromStdString
actually uses QString::fromUtf8
under the hood to convert to proper unicode.)