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() [qt-project.org] and QString::fromStdWString() [qt-project.org].

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:

  1. /*! Convert a QString to an std::wstring */
  2. std::wstring qToStdWString(const QString &str)
  3. {
  4. #ifdef _MSC_VER
  5.  return std::wstring((const wchar_t *)str.utf16());
  6. #else
  7.  return str.toStdWString();
  8. #endif
  9. }
  10.  
  11. /*! Convert an std::wstring to a QString */
  12. QString stdWToQString(const std::wstring &str)
  13. {
  14. #ifdef _MSC_VER
  15.  return QString::fromUtf16((const ushort *)str.c_str());
  16. #else
  17.  return QString::fromStdWString(str);
  18. #endif
  19. }

Note that for other platforms the std::wstring may be implemented using uint32 (for ucs-4/utf-32) instead.

Categories: