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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:09:25  来源:igfitidea点击:

Convert std::string to QString

c++stringqtutf-8qstring

提问by Fred Foo

I've got an std::string contentthat 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?

我有一个std::string content我知道包含 UTF-8 数据的文件。我想将其转换为QString. 我该怎么做,避免 Qt 中的 from-ASCII 转换?

回答by Hymanpap

QString::fromStdString(content)is better since it is more robust. Also note, that if std::stringis 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

There's a QStringfunction called fromUtf8that takes a const char*:

有一个QString名为的函数fromUtf8需要一个const char*

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

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