首页 > 解决方案 > 如何在 Windows 上将 Qt QString 转换为 LPCTSTR

问题描述

我试图打开注册表并修改它。这是我打开注册表的方式:

HKEY hKey;
LPCTSTR subKey = TEXT("a registry subkey to be opened");
RegOpenKeyEx(HKEY_LOCAL_MACHINE, subKey, 0, KEY_ALL_ACCESS , &hKey);

但是这里有一个问题,我想用aQString来务实地改变子键。并把QString这样的:

QString subKeyString = QString("%1").arg(subKeyName);
LPCTSTR subKey = TEXT(subKeyString); //but it's not working here

我认为这是因为我没有更改QStringto LPCTSTR,我尝试了这个解决方案,但我仍然无法找到将自定义QString放入TEXT宏的方法。我不太确定引擎盖下的 WinApi,我只是尝试了我可能做的事情。

有没有办法解决这个问题?

编辑:
这是我转换QStringLPCTSTR

QString testString = "converting QString to LPCSTR";
QByteArray testStringArr = testString.toLocal8Bit();
LPCSTR lp = LPCSTR(testStringArr.constData()); //the QString is converted to LPCTSTR
//but when I put the LPCSTR to the TEXT macro, the error is still there, like the next line below will not complie
LPCSTR lp = TEXT(LPCSTR(testStringArr.constData())); //This line will not work

标签: c++windowsqtqt5

解决方案


TEXT()宏仅适用于编译时文字,不适用于运行时数据。 TCHAR和相关的 API 旨在帮助人们将他们的代码从基于 ANSI 的 Win9x/ME 迁移到基于 Unicode 的 WinNT 4+,通过在 和 之间映射文字char,以及在和变体wchar_t之间映射函数名称。但那些日子早已一去不复返了。AW

在这种情况下,正确的解决方案是完全忽略TCHAR并只关注 Unicode。AQString是 Unicode 字符串的包装器。因此,仅使用基于 Unicode 的 Registry API 函数并假装TCHAR不存在。

在 Windows 上,基于 Unicode 的 API 需要 UTF-16 编码的wchar_t字符串。使用该QString::toStdWString()方法获取 a std::wstring,它是一个wchar_t字符串的 C++ 包装器:

QString subKeyString = QString("%1").arg(subKeyName);
std::wstring subKey = subKeyString.toStdWString();
HKEY hKey;
RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey.c_str(), 0, KEY_ALL_ACCESS, &hKey);

或者,您可以使用该QString::utf16()方法。但是,它返回一个const ushort*指针,因此您必须将其类型转换为const wchar_t*

QString subKeyString = QString("%1").arg(subKeyName);
LPCWSTR subKey = reinterpret_cast<LPCWSTR>(subKeyString.utf16());
HKEY hKey;
RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey, 0, KEY_ALL_ACCESS, &hKey);

推荐阅读