Qt下QString转char*

Qt下面,字符串都用QString,确实给开发者提供了方便,想一想VC里面定义的各类变量类型,并且函数参数类型五花八门,常常须要今年新那个类型转换html

Qt再使用第三方开源库时,因为库的类型基本上都是标准的类型,字符串遇的多的就是Char*类型编程

在Qt下怎样将QString转char*呢,须要用到QByteArray类,QByteArray类的说明详见Qt帮助文档。windows

由于char*最后都有一个‘/0’做为结束符,而采用QString::toLatin1()时会在字符串后面加上‘/0’函数

方法以下:post

Qstring  str;测试

char*  ch;编码

QByteArray ba = str.toLatin1();    .net

ch=ba.data();code

这样就完成了QString向char*的转化。经测试程序运行时不会出现bughtm

注意第三行,必定要加上,不能够str.toLatin1().data()这样一部完成,可能会出错。

 

补充:以上方法当QString里不含中文时,没有问题,可是QString内含有中文时,转换为char*就是乱码,采用以下方法解决:

方法1:

添加GBK编码支持:

#include <QTextCodec>

QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));

而后改变上面的第三行为:QByteArray ba = str.toLoacl8Bit();      toLoacl8Bit支持中文

方法2:

先将QString转为标准库中的string类型,而后将string转为char*,以下:

std::string str = filename.toStdString();

const char* ch = str.c_str();

参考:
http://www.cnblogs.com/Romi/archive/2012/03/12/2392478.html
http://www.cppblog.com/wicbnu/archive/2011/03/16/141956.aspx

-------------------------------------------------------------------------------------------

今天这个方法试了,仍是没有成功,我用过toLatin1(),toAscii(),toLocal8Bit(),均没有成功
换成先用std::string存储字符串,而后转成char*,成功了
http://blog.csdn.net/gzshun/article/details/8526675

-------------------------------------------------------------------------------------------

在windows下的QT编程中的_TCHAR与QString之间的转换因为在windows下的QT编程中,若是涉及到使用微软的API,那么不可避免使用_TCHAR这些类型,所以在网上查了一下,其中一个老外的论坛有人给出了这个转换,所以在这里作一下笔记 : )#ifdef UNICODE#define QStringToTCHAR(x) (wchar_t*) x.utf16()#define PQStringToTCHAR(x) (wchar_t*) x->utf16()#define TCHARToQString(x) QString::fromUtf16((x))#define TCHARToQStringN(x,y) QString::fromUtf16((x),(y))#else#define QStringToTCHAR(x) x.local8Bit().constData()#define PQStringToTCHAR(x) x->local8Bit().constData()#define TCHARToQString(x) QString::fromLocal8Bit((x))#define TCHARToQStringN(x,y) QString::fromLocal8Bit((x),(y))#endif参考:http://blog.csdn.net/itjobtxq/article/details/8465194

相关文章
相关标签/搜索