How to convert CString ATL / MFC to QString?

Given that the project encoding is probably Unicode (but not required), what is the best way to convert ATL :: CString to QString?

What I was thinking about 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 this works? Any other ideas?

+5
source share
1 answer

You do not need an intermediate conversion to std::string. A class CStringcan be thought of as a simple C-style string; i.e. an array of characters. All you have to do is drop it before LPCTSTR.

, QString , CString char wchar_t. QString, fromWCharArray function.

- (untested, Qt):

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

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

: , " wchar_t " "", Visual Studio ().

_UNICODE, , fromUtf16:

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

All Articles