Monday, April 12, 2010

Code snippets about QString, wchar_t *, TCHAR and others

QString to wchar_t *:
const wchar_t * encodedName = reinterpret_cast<const wchar_t *>(fileName.utf16());

QString to char * given a file name:
QByteArray fileName = QFile::encodeName(aFileName);
const char * encodedName = fileName.constData(); //Valid as long as fileName exists

QString to char * (general case):
const char * tmp = str.toUtf8().constData();

Windows Data Types: http://msdn.microsoft.com/en-us/library/aa383751.aspx

TCHAR:
#ifdef UNICODE
    typedef wchar_t TCHAR;
#else
    typedef char TCHAR;
#endif

LPCTSTR:
#ifdef UNICODE
    typedef LPCWSTR LPCTSTR; 
#else
    typedef LPCSTR LPCTSTR;
#endif

LPCSTR:
typedef const char * LPCSTR;

LPCWSTR:
typedef const wchar_t * LPCWSTR;

LPCWSTR to QString:
QString text(QString::fromUtf16(reinterpret_cast<const unsigned short *>(tmp)));
Another solution is to use QString::fromWCharArray() but this can leads to some unresolved symbols because of wchar_t.

More infos about UNICODE under Windows here

Best practice under Windows: define UNICODE, use wchar_t and L macro (L"text" defines a UNICODE string "text").

0 comments: