ToStdWStringAndBuiltInWchar: Difference between revisions
Jump to navigation
Jump to search
AutoSpider (talk | contribs) (Convert ExpressionEngine links) |
AutoSpider (talk | contribs) (Decode HTML entity names) |
||
Line 16: | Line 16: | ||
<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 26: | Line 26: | ||
/*! 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 and built-in wchar_t
Problem statement
Qt advises to build your Qt based software without wchar_t as built-in type, just like the Qt libraries themselves. In some cases this is not desired by the environment or not possible because other libraries have been built with the built-in wchar_t type. This will cause obscure linker errors when using std::wstrings, and QString::toStdWString() and QString::fromStdWString().
Possible solution
Windows uses utf-16 for its character encoding, as does Qt. Using this information we can use the following code to work around the issue:
/*! 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
}