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