Convert std::string to QString

丶灬走出姿态 提交于 2019-12-17 10:59:19

问题


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?


回答1:


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

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



回答2:


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())).




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/4338067/convert-stdstring-to-qstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!