简体   繁体   English

将std :: string转换为QString

[英]Convert std::string to QString

I've got an std::string content that I know contains UTF-8 data. 我有一个std::string content我知道包含UTF-8数据。 I want to convert it to a QString . 我想将它转换为QString How do I do that, avoiding the from-ASCII conversion in Qt? 我该怎么做,避免Qt中的from-ASCII转换?

有一个名为fromUtf8QString函数,它接受一个const char*

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

QString::fromStdString(content) is better since it is more robust. QString::fromStdString(content)更好,因为它更健壮。 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())) . 另请注意,如果std::string以UTF-8编码,那么它应该提供与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. 通常,执行转换的最佳方法是使用fromUtf8中的方法,但问题是当您具有依赖于语言环境的字符串时。

In these cases, it's preferable to use fromLocal8Bit . 在这些情况下,最好使用fromLocal8Bit Example: 例:

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

Since Qt5 fromStdString internally uses fromUtf8, so you can use both: 由于Qt5 fromStdString内部使用fromUtf8,所以你可以同时使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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