如何将 ATL/MFC CString 转换为 QString? [英] How do I convert an ATL/MFC CString to a QString?

查看:52
本文介绍了如何将 ATL/MFC CString 转换为 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.

一旦你有了它,你只需要根据CString中的字符是否属于char类型来创建QString对象或 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆