【问题标题】:QString::fromStdString returns broken textQString::fromStdString 返回损坏的文本
【发布时间】:2020-10-15 07:09:45
【问题描述】:

在我的 Qt GUI 应用程序中,我使用 libwebrtc。从一个回调开始,我想用数据发出信号,即 std::string。由于核心应用程序逻辑使用 QString,我想将 std::string 转换为 Qstring。 我尝试以下:

QString::fromStdString(stdstr)
QString::fromLatin1(stdstr.data())

这两个都返回损坏的文本,例如this

对我来说唯一的工作方式是

QString qstr;
for(uint i =0; i< stdstr.length(); i++)
    qstr.append(stdstr.at(i));

这里是我对问题原因的看法:

  1. 编码问题。
  2. 二进制问题

关于编码,libwebrtc 应该默认返回 UTF-8 格式的 std::string,和 QString 一样。

关于二进制。据我了解,Qt 是用 GCC 和相应的 stdlib 构建的,但 libwebrtc 是用 CLang 和 libc++ 构建的。对于构建,我还指定使用 QMAKE_CXXFLAGS += -stdlib=libc++

在这里转换类型的正确方法是什么?

UPD

我比较了转换后的字符串和源字符串的长度,它们有很大的不同。

对于 std::string 我得到 64,对于转换后的 QString 我得到 5。

UPD2

这里是 SPDGen 信号的完整功能和对应的槽

void foo(const webrtc::IceCandidateInterface *candidate) override {
    std::string str;
    candidate->ToString(&str);
    QString qstr = QString::fromStdString(str);
    qDebug() << qstr;
    Q_EMIT SPDGen(qstr);
}

connect(conductor, &Conductor::SPDGen, this, [=](QString value){
    ui->textEdit->setText(value);
});

【问题讨论】:

  • 可能是编码问题。您是否尝试过:QString::fromUtf8(stdstr.data());
  • @vahancho 是的,我也尝试过QString::fromUtf8QString::fromLatin1QString::fromLocal8Bit。他们也返回不正确的数据。
  • stdstr的内容是什么?能举个例子吗?
  • @vahancho 这是我获取此字符串数据的方式 ` void foo(const webrtc::IceCandidateInterface *candidate) override { std::string str;候选人->ToString(&str); ... } ` 这里是包含的实际数据:candidate:3800372419 1 tcp 1518280447 192.168.126.9 46851 typ ho
  • 请显示您的foo() 函数中的完整代码。顺便说一句,你的字符串看起来不错,我什至没有看到任何非 ASCII 字符。

标签: qt


【解决方案1】:

我在您的代码 sn-ps 中没有看到任何 QString::fromStdString,所以我假设您打错了(因为 QString::fromStrString 不在文档中)。 无论如何,这里回答了一个(非常)类似的问题:

How to change string into QString?

【讨论】:

  • 是的,这只是一个错字,我使用QString::fromStdString
猜你喜欢
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2020-02-26
  • 1970-01-01
  • 2020-06-23
相关资源
最近更新 更多