首页 > 解决方案 > 删除 unicode def 后无法将 QString 转换为 TCHAR

问题描述

以前当我声明 unicode 时,我能够执行以下操作

QString myPassword = "123";
TCHAR szPassword[32];

myPassword.toWCharArray(szPassword);

但是在我删除了我的 uncode def 之后,我得到了以下错误

 error C2664: 'QString::toWCharArray' : cannot convert parameter 1 from 
'TCHAR [32]' to 'wchar_t *'

我现在如何将我的 Qstring 转换为 TCHAR 数组?

标签: c++qt

解决方案


Qt 提供了几种在QStringWindows 标准和 UTF16-LE 之间进行转换的方法:

转换为 C++ std::wstring

QString myPassword = "abcd ελληνικά";
std::wstring wstr = myPassword.toStdWString();
MessageBoxW(0, wstr.c_str(),0,0);

对于 using toWCharArray,输入缓冲区必须有足够的内存并且必须以空值结尾:

wchar_t buf[100] = {0};
myPassword.toWCharArray(buf);
MessageBoxW(0, buf,0,0);

或者使用QString::utf16()返回的方法const unsigned short*,它需要const wchar_t*强制转换:

MessageBoxW(0, (const wchar_t*)myPassword.utf16(), 0, 0);

注意,TCHAR是一个令人困惑的 Windows 宏,它被定义char为 ANSI 程序和wchar_tUnicode 程序。避免使用它。


推荐阅读