Qt下QString转char*

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

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

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

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

方法如下:

Qstring  str;

char*  ch;

QByteArray ba = str.toLatin1();    

ch=ba.data();

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

注意第三行,一定要加上,不可以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

原文地址:https://www.cnblogs.com/invisible2/p/6905914.html