如何将ATL / MFC CString转换为QString? [英] How do I convert an ATL/MFC CString to a QString?
问题描述
给定的项目的编码可能是Unicode(但不是肯定)什么是最好的方式转换ATL :: CString到QString?
Given the encoding of the project is probably Unicode (but not for sure) what is the best way of converting ATL::CString to QString?
我想到的是这样:
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?
推荐答案
您不需要中间转换为 std :: string
。 CString
类可以被视为一个简单的C风格字符串;即,字符的数组。所有你需要做的是把它转换为 LPCTSTR
。
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
.
一旦你有了,你只需要创建 QString
对象取决于 CString
中的字符是否为 char
或
wchar_t
。对于前者,您可以使用标准构造函数 QString
,对于后者,您可以使用 fromWCharArray
函数。
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.
类似下面的代码没有Qt安装):
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
编辑您必须禁用在项目的属性中将 wchar_t
作为内置类型,以使上述代码在Visual Studio中正确链接(来源)。
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).
对于 _UNICODE
,我相信您也可以使用 fromUtf16
功能:
For _UNICODE
, I believe you could also use the fromUtf16
function:
CString c(_T("SOME TEXT"));
QString q = QString::fromUtf16(c.GetBuffer(), c.GetLength());
这篇关于如何将ATL / MFC CString转换为QString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!