[Qt-interest] howto convert QString to char*

BRM bm_witness at yahoo.com
Tue Jul 13 19:57:49 CEST 2010


----- Original Message ----

> First of all,  you have to remember one important difference between QString 
>and 
>
> char*:  QString stores data in UTF-16, while char* is just arbitrary 8-bit 
> data.
> 
> So to convert from QString to char*, the first thing you need  to know is the 
> encoding. What encoding is the data that you want?
> 
> If  it's Latin 1 (ISO-8859-1), you can use toLatin1. If it's UTF-8, you can use 
>
> toUtf8(). If it's the locale encoding, you can use toLocal8Bit(). Otherwise, 
> you should use QTextCodec to find the appropriate codec to  convert.
> 
> Once you know the encoding, you can get a QByteArray with the  data that you 
> want. QByteArray is a class that holds a char* and manages its  memory.
> 
> If the value must persist, you should either keep the QByteArray,  or you 
> should copy it before the QByteArray goes out of scope.
> 
> If it  doesn't have to persist, then usually it's enough to simply use 
> QByteArray's  automatic casting to char*. So if the encoding you needed was 
> Latin1, you'd  write:
> 
>      SomeDllFunction(string.toLatin1());
> 
> That's all.

Interesting; however, that has never seemed to work for me - I usually get 
compilation issues; so I typically just do:

QString qtString = "someString";
std::string stdCString = qtString.toStdString();
char* charPtr = stdCString.data();
// charPtr is only good while stdCString (i) doesn't change, and (ii) remains in 
scope

Ben




More information about the Qt-interest-old mailing list