How do I convert an ATL/MFC CString to a QString?

Hayri Uğur Koltuk picture Hayri Uğur Koltuk · Jun 2, 2011 · Viewed 7.2k times · Source

Given the encoding of the project is probably Unicode (but not for sure) what is the best way of converting ATL::CString to QString?

What I have thought of is this:

CString c(_T("SOME_TEXT"));
//...
std::basic_string<TCHAR> intermediate((LPCTSTR)c);
QString q;

#ifdef _UNICODE 
q = QString::fromStdWString(intermediate);
#else
q = QString::fromStdString(intermediate);
#endif

Do you think that it works? Any other ideas?

Answer

Cody Gray picture Cody Gray · Jun 2, 2011

You don't need the intermediate conversion to a std::string. The CString class can be treated as a simple C-style string; that is, an array of characters. All you have to do is cast it to an LPCTSTR.

And once you have that, you just need to create the QString object depending on whether the characters in your CString are of type char or wchar_t. For the former, you can use one of the standard constructors for QString, and for the latter, you can use the fromWCharArray function.

Something like the following code (untested, I don't have Qt installed anymore):

CString c(_T("SOME_TEXT"));
QString q;

#ifdef _UNICODE 
q = QString::fromWCharArray((LPCTSTR)c, c.GetLength());
#else
q = QString((LPCTSTR)c);
#endif

Edit: As suggested in the comments, you have to disable "Treat wchar_t as a built-in type` in your project's Properties to get the above code to link correctly in Visual Studio (source).

For _UNICODE, I believe you could also use the fromUtf16 function:

CString c(_T("SOME TEXT"));
QString q = QString::fromUtf16(c.GetBuffer(), c.GetLength());