简体   繁体   中英

Convert std::string to QString

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?

有一个名为fromUtf8QString函数,它接受一个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())) .

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()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM