接着前篇:http://blog.csdn.net/bzhxuexi/article/details/17111903
在前篇中遇到了一个问题,当时没解决,今天终于找到了解决方法,我在网上看到了这样的一段解释,源自于QT Center,是这样的:
rajeshs ask a question:
How can I convert a QString to char* and vice versa ?
Answer:
In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in the byte array. See the documentation:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLatin1();
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.toLatin1().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, e.g:
QString string = QString(QLatin1String(c_str2)) ;
上面代码中的加粗蓝色句子是关键,好多人都知道QString 转 const char*要经过两步:
(1)先通过toLatin1()或toAscii()方法转为QByteArray();
(2)再通过data()或constData()方法
就转换成了const char *。
但是,好多人都这样写的代码:
QString str;
const char *s = str.toLatin1().data();
或 const char *s = str.toAscii().data();
这样的话,str.toLatin1()的内容没有存储,就直接调用了data()方法。因此,结果就为空或者乱码。
正确的写法应该是这样的:
----------------------------------------------------------------------
QString str;
QByteArray aByteArray = str.toLatin1();//先把转化为QByteArray的结果存储起来
const char *s = aByteArray.data();//再调用data()或constData()
------------------------------------------------------------------------------------
或者:
QString str;
QByteArray aByteArray = str.toAscii();//先把转化为QByteArray的结果存储起来
const char *s = aByteArray.data();//再调用data()或constData()
--------------------------------------------------------------------------------------------------------------------
Append:
今天找到了一个更好的解决方法:
QString str;
const char *temStr = str.toLocal8Bit();//(1)
qDebug()<<temStr;//(2)
这样,(2)处打印出来也是乱码,但是,可以这样直接把str.toLocal8Bit()放到你要用到const char *的地方,就可以了,我试了,能正常工作。
刚开始,看到qDebug出来的是乱码,以为不能用,后来发现不影响正常使用。