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?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Hayri Uğur Koltuk
  • 2,970
  • 4
  • 31
  • 60

1 Answers1

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());
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Thanks :) Any ideas on why QString::fromWCharArray does not link? Strangely, It is the only function that linker cannot find... – Hayri Uğur Koltuk Jun 02 '11 at 14:48
  • @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. – Cody Gray - on strike Jun 02 '11 at 14:51
  • No no, i found the reason. it is [here](http://www.qtcentre.org/threads/4625-WCHAR-to-QString-giving-error-in-vs2005) – Hayri Uğur Koltuk Jun 02 '11 at 14:53
  • @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. – Cody Gray - on strike Jun 02 '11 at 14:55
  • 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. – Hayri Uğur Koltuk Jun 02 '11 at 15:00