- All (478)
- jom (0)
- Qt Linguist (7)
- Qt Eclipse Integration (9)
- Qt Designer (7)
- Qt Creator (4)
- Qt build system: qmake (31)
- Qt build system: configure (3)
- Qt Assistant (5)
- Printing (4)
- Porting from Qt 3 to Qt 4 (1)
- Plugins (7)
- Qt Visual Studio AddIn (2)
- Qt/MFC Migration (2)
- QtScript (3)
- MDI (2)
- XML (1)
- Widgets (22)
- WebKit (5)
- Tools and Containers (2)
- Threads (2)
- Text Handling (10)
- SQL (6)
- QtTest (1)
- QtService (1)
- Platform: Windows (49)
- Platform: Unix (16)
- Platform: Mac OS X (18)
- Image Formats (2)
- I/O (2)
- Graphicsview (8)
- Font handling (9)
- Event System (18)
- Drag and Drop (4)
- Dialogs (6)
- Desktop integration (3)
- ActiveQt (3)
- Itemviews (60)
- Layout (4)
- Qt Quick (10)
- Qt SDK (1)
- Licensing (2)
- Platform: Embedded Linux (38)
- Painting (32)
- OpenGL (4)
- Object Model (6)
- Network (5)
- Multimedia (3)
- Miscellanous (23)
- Main Window (19)
- Look and Feel (23)
- Development (0)
- Getting Involved (0)
- Routines (0)
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:
- int main(int argc, char **argv)
- {
- const char *c_str2 = ba.data();
- printf("str2: %s", c_str2);
- return app.exec();
- }
Note that it is necessary to store the bytearray before you call data() on it, a call like the following
- 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:
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:
- printf("str2: %s", qPrintable(str1));

3 comments
April 29, 2011
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
Robot Herder
The post above contains a memory leak. Here is the corrected version:
May 2, 2011
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.