How to convert QString to std::string?

augustin picture augustin · Nov 18, 2010 · Viewed 298.6k times · Source

I am trying to do something like this:

QString string;
// do things...
std::cout << string << std::endl;

but the code doesn't compile. How to output the content of qstring into the console (e.g. for debugging purposes or other reasons)? How to convert QString to std::string?

Answer

Pablo Santa Cruz picture Pablo Santa Cruz · Nov 18, 2010

You can use:

QString qs;
// do things
std::cout << qs.toStdString() << std::endl;

It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well. Here's reference documentation for QString.