加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将QString转换为std :: string

发布时间:2020-12-16 05:01:29 所属栏目:百科 来源:网络整理
导读:我已经看过其他几篇关于将QString转换为std :: string的帖子,它应该很简单.但不知怎的,我收到了一个错误. 我的代码使用cmake编译成一个VS项目(我正在使用VS express),所以QT库没有问题,我编写的GUI除了这部分之外还有用. 我有一个QComboBox cb,它包含一些对
我已经看过其他几篇关于将QString转换为std :: string的帖子,它应该很简单.但不知怎的,我收到了一个错误.

我的代码使用cmake编译成一个VS项目(我正在使用VS express),所以QT库没有问题,我编写的GUI除了这部分之外还有用.

我有一个QComboBox cb,它包含一些对象的名称,还有一个QLineEdit lineEdit,它允许我指定我要查找的对象的名称.当我按下一个go按钮时,它应该运行一个经过测试和工作的函数,其中来自QComboBox和lineEdit的输入作为参数.

这是单击go按钮时的代码:

void gui::on_go_clicked(){
    std::string str(cb->currentText().toStdString());
    //std::cout << str << "n";
    //QString qstr = lineEdit->text();
    //std::cout<<lineEdit->text().toStdString();
    updateDB(str,lineEdit->text().toStdString());
}

创建str的第一行工作正常. I.E.库函数或toStdString()没有问题.但是当它执行我的函数时,程序会中断,并且它不是因为函数,因为它试图转换lineEdit-> text().toStdString()的部分.

这只是当我在lineEdit框中写下“test”时.我已经看到其他答案谈论unicode,我曾尝试过,但我可以假设用户不会在lineEdit框中添加任何特殊字符,除非’_’和’.’,它们不应该是unicode.

解决方法

The first line,creating str,works fine. I.E. there’s no problem with
library functions or toStdString(). But when it executes my function,
the program breaks,and it’s not becuase of the function,it’s because
of the part where it tries to convert lineEdit->text().toStdString().

简化您的测试并验证QString.toStdString()是否符合您的预期:

因此:

QString text = "Precise text that user would input";
std::cout << text.toStdString() << std::endl; //or...
qDebug() << text.toStdString().c_str();

是否产生了预期结果?

如果是这种情况,则表示您的功能存在问题. updateDB看起来如何(函数签名?)?它的投入是什么?

从Qt帮助文件:

The Unicode data is converted into 8-bit characters using the toUtf8() function.

因此,如果您没有更改窗口小部件(lineEdit)或其父窗口的区域设置,那么事情应该正常工作(或者您应该看到信息丢失的内容).我已多次使用此功能而没有麻烦……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读