将 std::string 转换为 QString

发布于 2024-10-05 21:04:59 字数 186 浏览 1 评论 0原文

我知道 std::string content 包含 UTF-8 数据。我想将其转换为 QString。我该如何做到这一点,避免 Qt 中的 from-ASCII 转换?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

那支青花 2024-10-12 21:04:59
QString::fromStdString(content)

这更好,因为它更稳健。

另请注意,如果 std::string 以 UTF-8 编码,那么它应该给出与 QString::fromUtf8(content.data(), int(content.大小()))

QString::fromStdString(content)

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

素年丶 2024-10-12 21:04:59

有一个名为 fromUtf8QString 函数需要一个 const char*

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

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

QString str = QString::fromUtf8(content.c_str());
夜清冷一曲。 2024-10-12 21:04:59

由于 Qt5 fromStdString 内部使用 fromUtf8,因此您可以同时使用两者:

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

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()));
}
谁的新欢旧爱 2024-10-12 21:04:59

通常,进行转换的最佳方法是使用方法 fromUtf8,但问题是当你的字符串依赖于语言环境时。

在这些情况下,最好使用 fromLocal8Bit。例子:

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

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());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文