[Qt-interest] QString and Unicode literals

Jochen Roemmler jochen444 at concept.de
Fri May 29 14:39:49 CEST 2009


Hello Robert,

> Are Unicode literals meant to work with a QString?

I think in general, yes.

> For example, I
> would expect the following to set the string to "Test" followed by the
> Euro character:
> 
> QString str("Test\u20AC");

I think its all explained in the docs:
http://doc.trolltech.com/4.5/qstring.html#QString-7

The default behavior of converting your literal C string "Test\u20AC"
into QString's Unicode representation is: assume latin1 encoding.
You can change that by installing a text codec with

void QTextCodec::setCodecForCStrings(QTextCodec* codec) [static]

> QString str("Test");
> test += QChar(0x20AC);
> 
> Is this a bug or is this behaviour by design?  Is there another way to
> embed Unicode literals in a QString?

Sure, assuming UTF-8 encoding:

#include <QtCore>
#include <QtDebug>

int main(int argc, char* argv[])
{
    QCoreApplication app(argc, argv);
    QTextCodec* codec = QTextCodec::codecForName("UTF-8");
    if (!codec) return 1;
    QString str = QString::fromUtf8("Test \u20AC");
    qDebug() << str;
    return 0;
}

worked for me (terminal character encoding set to UTF-8, of course).

-- 
Regards,
Jochen



More information about the Qt-interest-old mailing list