Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't QString treat special characters correctly, when no QCoreApplication has been instantiated?

I started writing a very basic text manipulation application in Qt, without a GUI. My text contained special characters, but somehow I was not able to print those special characters, no matter what I did. I then noticed, that after adding a QCoreApplication instance (which I had previously removed, because I thought I wouldn't need it), everything worked just as it should.

Here is the code:

#include <QCoreApplication>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString s(QString::fromUtf8("aä\xc3\xa4")); // aää

    qDebug() << s;
    qDebug() << s.toAscii();
    qDebug() << s.toLatin1();
    qDebug() << s.toUtf8();
    qDebug() << s.toLocal8Bit();
    qDebug("%s", qPrintable(s));

    qDebug("%i", s.length());
    qDebug("%i", strlen(qPrintable(s)));

    return 0;
}

Output with QCoreApplication (everything works as it should):

"aää" 
"aää" 
"aää" 
"aää" 
"aää" 
aää
3
5

Output after commenting out the line, where QCoreApplication is defined (special characters are not shown anymore):

"a" 
"a" 
"a" 
"a" 
"a" 
a
3
1

Note, that already after calling qPrintabable(s), the special characters are already removed. I tested this to be sure, that QDebug is not the problem.

I also checked if the file is really encoded in UTF-8.

Why doesn't QString treat special characters correctly, when no QCoreApplication has been instantiated?

like image 209
Misch Avatar asked Oct 04 '12 15:10

Misch


1 Answers

After going through Qt's source code, I stumbled across this code called when QCoreApplication is constructed:

#ifdef Q_OS_UNIX
    setlocale(LC_ALL, "");                // use correct char set mapping
    qt_locale_initialized = true;
#endif

In other words, on "Unix" systems, the QCoreApplication constructor is making a call to setlocale (found in locale.h), which is used to set the program's current locale. This ultimately affects the output from qDebug, which relies on QTextStream, which ultimately uses what it believes is the system-defined locale to create its output.

When I tested your code on a Linux system, I encountered the same result that you did. On a Windows system, commenting-out the QCoreApplication construction had no impact on the results. I also noticed that printing out the original string through printf gave the correct result regardless of whether QCoreApplication was constructed.

like image 109
RA. Avatar answered Oct 31 '22 23:10

RA.