PDA

View Full Version : How to convert QString to const char*



fulin
7th May 2010, 13:33
Can anyone tell me how to convert QString to const char*?

for example

QString mystring;

I tried

mystring.data(); mystring.toLatin1(); mystring.toAscii();

none of them work.:o

csaken
7th May 2010, 15:36
I just tried:



QString a("Asdf");
const char *c = a.toAscii();


It seems to work.

erhan
7th May 2010, 15:39
You can use qPrintable macro.

ChrisW67
8th May 2010, 08:51
mystring.data(); // returns QChar*
mystring.toLatin1(); // returns QByteArray
mystring.toAscii(); // returns QByteArray
none of them work.:o
They all work, but they are not designed to give you a char* (const or otherwise). You want to read the relevant parts of the QByteArray docs and:


char *str1 = mystring.toLatin1().data();
char *str2 = mystring.toAscii().data();

coolkaps
9th May 2010, 16:54
simply use
QString l_sStr = "Hello";
const char* test = l_sStr.toLatin1().data(); // in Qt4
const char* test = l_sStr.tolatin1();//in Qt3l

wysota
9th May 2010, 22:13
Most of what is said in this thread is wrong, guys. I'll give you a hint - storing a pointer to data from a temporary object may lead to a crash.

squidge
9th May 2010, 22:43
Been there, done that, got the T-Shirt. Watched the application create a temporary QByteArray, grab the pointer to the constant data of the QByteArray and then the QByteArray was destroyed before the next line of code was executed, thus the pointer was no longer valid. Random crashes and garbage data from that point on. Now I'm very care about such things.

ChrisW67
9th May 2010, 23:25
Most of what is said in this thread is wrong, guys. I'll give you a hint - storing a pointer to data from a temporary object may lead to a crash.

D'oh! At least that's all I was going to say before the ten character reply limit kicked in ;)