C++ 将 std::string 转换为 QString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4338067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert std::string to QString
提问by Fred Foo
回答by Hymanpap
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
以 UTF-8 编码,则它应该给出与QString::fromUtf8(content.data(), int(content.size()))
.
回答by Michael Mrozek
回答by Tarod
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. Example:
在这些情况下,最好使用fromLocal8Bit。例子:
std::string str = "?xample";
QString qs = QString::fromLocal8Bit(str.c_str());
回答by maxa
Since Qt5fromStdString internally uses fromUtf8, so you can use both:
由于Qt5fromStdString 内部使用 fromUtf8,因此您可以同时使用两者:
inline QString QString::fromStdString(const std::string& s)
{
return fromUtf8(s.data(), int(s.size()));
}