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

1

5

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?

Schoolgirl answered 2/6, 2011 at 14:23 Comment(1)
actually no because for some reason i cannot link. before trying to link it, i wanted to ask if i am on the correct wayMultipurpose
K
9

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());
Kc answered 2/6, 2011 at 14:44 Comment(5)
Thanks :) Any ideas on why QString::fromWCharArray does not link? Strangely, It is the only function that linker cannot find...Multipurpose
@Ali: Perhaps you're using an older version of Qt that doesn't include that function? While you were leaving that comment, I added another possible solution. You might try that instead.Kc
No no, i found the reason. it is hereMultipurpose
@Ali: Fascinating, I never would have guessed that. Still not sure I understand why it's necessary. I guess the VS compiler treats wchar_t differently than Qt is expecting.Kc
Yep, i think so. I guess wchar_t is some typedef and when it is built-in, linker looks for the function which takes built in type parameter rather than typedef type parameter. i believe that's why it does not link.Multipurpose

© 2022 - 2024 — McMap. All rights reserved.