QT QString与char *之间的转换 .

http://blog.csdn.net/candyliuxj/article/details/6429208

 

 

1.QString转char *

先将QString转换为QByteArray,再将QByteArray转换为char *。

注意:不能用下面的转换形式char *mm = str.toLatin1().data();。因为这样的话,str.toLatin1()得到的QByteArray类型结果就不能保存,最后转换,mm的值就为空。

 

2. char * 转QString

可以使用QString的构造函数进行转换:QString(const QLatin1String &str);

QLatin1String的构造函数:QLatin1String(const char *str);

则如下语句是将char * mm转换为QString str:

str = QString(QLatin1String(mm));

 

 

 

例子:

 

  1. //#include "myclass.h"   
  2. #include <QtGui/QApplication>   
  3. #include <QtDebug>   
  4. #include <QString>   
  5.   
  6. int main(int argc, char *argv[])  
  7. {  
  8.     QApplication a(argc, argv);  
  9.   
  10.     QString str = “hello”; //QString转char *   
  11.      QByteArray ba = str.toLatin1();  
  12.     char *mm = ba.data();  
  13.     qDebug()<<mm<<endl;  //调试时,在console中输出   
  14.   
  15.       QString nn = QString(QLatin1String(mm)); //char *转QString   
  16.     qDebug()<<nn<<endl;  //调试时,在console中输出   
  17.   
  18.     //MyClass w;   
  19.     //w.show();   
  20.     return a.exec();  
  21. }  

 

进行调试,在console处输出如下内容:

hello

hello

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值