Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.
ToStdWStringAndBuiltInWchar/zh: Difference between revisions
Jump to navigation
Jump to search
AutoSpider (talk | contribs) (Add "cleanup" tag) |
AutoSpider (talk | contribs) (Decode HTML entity names) |
||
Line 18: | Line 18: | ||
<code>/*! Convert a QString to an std::wstring */ | <code>/*! Convert a QString to an std::wstring */ | ||
std::wstring qToStdWString(const QString & | std::wstring qToStdWString(const QString &str) | ||
{ | { | ||
#ifdef _MSC_VER | #ifdef _MSC_VER | ||
Line 28: | Line 28: | ||
/*! Convert an std::wstring to a QString */ | /*! Convert an std::wstring to a QString */ | ||
QString stdWToQString(const std::wstring & | QString stdWToQString(const std::wstring &str) | ||
{ | { | ||
#ifdef _MSC_VER | #ifdef _MSC_VER |
Revision as of 17:53, 12 March 2015
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine. Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean. |
简体中文 English
QString、std::wstring 与内置的 wchar_t
问题陈述
Qt 建议我们构建基于Qt的软件时,像Qt库自身一样,不要将 wchar_t 作为内置类型。在一些情况下,这不是所期待的,或者是不可能的,因为其他的库构建时可能已经将 wchar_t 作为了内置类型。当使用 std::wstring、QString::toStdWString()和 QString::fromStdWString() 将导致链接错误.
可能的解决方案
Windows 使用 utf-16 作为本身字符的编码,Qt也是如此。借助这个信息我们可以使用下面的代码来规避这个问题:
/*! Convert a QString to an std::wstring */
std::wstring qToStdWString(const QString &str)
{
#ifdef _MSC_VER
return std::wstring((const wchar_t''')str.utf16());
#else
return str.toStdWString();
#endif
}
/*! Convert an std::wstring to a QString */
QString stdWToQString(const std::wstring &str)
{
#ifdef _MSC_VER
return QString::fromUtf16((const ushort''')str.c_str());
#else
return QString::fromStdWString(str);
#endif
}
注意 std::wstring 在其他平台下可能使用 uint32 (对于ucs-4/utf-32) 来实现。