Convert QString to std :: string

I saw several other posts about converting QString to std :: string, and it should be simple. But for some reason I get an error message.

My code is compiled into a VS project using cmake (I use VS express), so there are no problems with QT libraries, and the graphical interface that I wrote works in addition to this part.

I have a QComboBox cb that contains the names for some objects, and a QLineEdit lineEdit that allows me to specify the name of the object I'm looking for. It should run a function that is tested and works when I press the go button, with the input of the QComboBox and lineEdit .

Here is the code for clicking the go button:

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

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

This is only when I write the word "test" in the lineEdit field. I saw other answers telling about unicode that I tried briefly, but I can assume that the user will not put any special characters in the lineEdit field, forbidding "_" and ".", Which should not be unicode.

+6
source share
1 answer

The first line that creates str works fine. I.E. no problem with library functions or toStdString (). But when it performs my function, the program breaks, and this is not because of the function, because of the part where it tries to convert lineEdit-> text (). toStdString ().

Simplify the test and make sure QString.toStdString () does what you expect:

In this way:

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

Is the expected result obtained?

If so, then your function has a problem. What does updateDB look like (function signature?)? What are its inputs?

From the Qt help files:

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

Therefore, if you have not changed the language standard of your widget (lineEdit) or its parents, everything should just work (or you should see something with a loss of information). I used this function many times without problems ...

+9
source

Source: https://habr.com/ru/post/952046/


All Articles