我有一个 std::string content包含 UTF-8数据。我想把它转换成 QString。如何做到这一点,避免 Qt 中的 from-ASCII 转换?
std::string content
QString
There's a QString function called fromUtf8 that takes a const char*:
fromUtf8
const char*
QString str = QString::fromUtf8(content.c_str());
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())).
QString::fromStdString(content)
std::string
QString::fromUtf8(content.data(), int(content.size()))
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());
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())); }