[英]How do I convert an ATL/MFC CString to a 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?鉴于项目的编码可能是 Unicode(但不确定)将 ATL::CString 转换为 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?
还有其他想法吗?
You don't need the intermediate conversion to a std::string
.您不需要中间转换为
std::string
。 The CString
class can be treated as a simple C-style string; CString
class 可以被视为简单的 C 风格字符串; that is, an array of characters.也就是一个字符数组。 All you have to do is cast it to an
LPCTSTR
.您所要做的就是将其转换为
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
.一旦你有了它,你只需要根据
CString
中的字符是char
还是wchar_t
类型来创建QString
object 。 For the former, you can use one of the standard constructors for QString
, and for the latter, you can use the fromWCharArray
function .对于前者,您可以使用
QString
的标准构造函数之一,对于后者,您可以使用fromWCharArray
function 。
Something like the following code (untested, I don't have Qt installed anymore):类似于以下代码(未经测试,我不再安装 Qt):
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 ).编辑:正如评论中所建议的,您必须在项目的属性中禁用“将
wchar_t
视为内置类型”,以使上述代码在 Visual Studio( 源代码)中正确链接。
For _UNICODE
, I believe you could also use the fromUtf16
function :对于
_UNICODE
,我相信您也可以使用fromUtf16
function :
CString c(_T("SOME TEXT"));
QString q = QString::fromUtf16(c.GetBuffer(), c.GetLength());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.