How can I convert a QString to char* and vice versa?

In order to convert a QString [doc.qt.nokia.com] to a char*, then you first need to get a local8Bit representation of the string by calling toLocal8Bit() [qt.nokia.com] on it which will return a QByteArray [doc.qt.nokia.com]. Then call data() [qt.nokia.com] on the QByteArray to get a pointer to the data stored in the byte array.

See the following example for a demonstration:

  1.     int main(int argc, char **argv)
  2.     {
  3.      QApplication app(argc, argv);
  4.       QString str1 = "Test";
  5.       QByteArray ba = str1.toLocal8Bit();
  6.       const char *c_str2 = ba.data();
  7.       printf("str2: %s", c_str2);
  8.       return app.exec();
  9.     }

Note that it is necessary to store the bytearray before you call data() on it, a call like the following

  1. const char *c_str2 = str2.toLocal8Bit().data();

will make the application crash as the QByteArray has not been stored and hence no longer exists

To convert a char* to a QString you can use the QString constructor that takes a QLatin1String [doc.qt.nokia.com] to ensure the locale encoded string is correct with fromLocal8Bit() [qt.nokia.com], e.g:

  1. QString string = QString(QLatin1String(c_str2));
  2. QString string = QString::fromLocal8Bit(c_str2);

In addition, if you want to just print out the string then you can use qPrintable() [qt.nokia.com] as a quick means to do this without having to convert to a char *. For example:

  1. printf("str2: %s", qPrintable(str1));

3 comments

April 29, 2011

Picture of dialingo dialingo

Robot Herder

Conversion of QString to char* depends on the encoding. In most cases UTF-8 is the right choice.
Therefore:

QString qString1 = “hello”;
const char *cString = qString1.toUtf8().constData();
QString qString2 = QString::fromUtf8(cString);

April 29, 2011

Picture of dialingo dialingo

Robot Herder

The post above contains a memory leak. Here is the corrected version:

  1. QString qString1 = "hello";
  2. QByteArray byteArray = qString1.toUtf8();
  3. const char* cString = byteArray.constData();
  4.  
  5. QString qString2 = QString::fromUtf8(cString);

May 2, 2011

Picture of AndyS AndyS

Lab Rat

I removed the comments pertaining to the original state of the FAQ and have now updated it to show toLocal8Bit() usage instead and added a note about qPrintable() too.

Write a comment

Sorry, you must be logged in to post a comment.