Convert std::string to QString

C++StringQtUtf 8Qstring

C++ Problem Overview


I've got an std::string content that I know contains UTF-8 data. I want to convert it to a QString. How do I do that, avoiding the from-ASCII conversion in Qt?

C++ Solutions


Solution 1 - C++

QString::fromStdString(content) is better since it is more robust. Also note, that if std::string is encoded in UTF-8, then it should give exactly the same result as QString::fromUtf8(content.data(), int(content.size())).

Solution 2 - C++

There's a QString function called fromUtf8 that takes a const char*:

QString str = QString::fromUtf8(content.c_str());

Solution 3 - C++

Since Qt5 fromStdString internally uses fromUtf8, so you can use both:

inline QString QString::fromStdString(const std::string& s) 
{
return fromUtf8(s.data(), int(s.size()));
}

Solution 4 - C++

Usually, the best way of doing the conversion is using the method fromUtf8, but the problem is when you have strings locale-dependent.

In these cases, it's preferable to use fromLocal8Bit. Example:

std::string str = "ëxample";
QString qs = QString::fromLocal8Bit(str.c_str());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFred FooView Question on Stackoverflow
Solution 1 - C++JackpapView Answer on Stackoverflow
Solution 2 - C++Michael MrozekView Answer on Stackoverflow
Solution 3 - C++maxaView Answer on Stackoverflow
Solution 4 - C++TarodView Answer on Stackoverflow