c – 将QString转换为std :: string

前端之家收集整理的这篇文章主要介绍了c – 将QString转换为std :: string前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经看过其他几篇关于将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@H_301_20@ library functions or toStdString(). But when it executes my function,@H_301_20@ the program breaks,and it’s not becuase of the function,it’s because@H_301_20@ 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)或其父窗口的区域设置,那么事情应该正常工作(或者您应该看到信息丢失的内容).我已多次使用此功能而没有麻烦……

猜你在找的C&C++相关文章