参考网址:http://blog.csdn.net/lfw19891101/article/details/6641785
(网页保存于:百度云CodeSkill33 --> 全部文件 > 来自__网页 > Qt5_for_Win > QString与中文问题__20151228_1432.rar)
1、
我的测试代码:
void MainWindow::on_pushButton_clicked() { // ZC: char* 转为 Unicode(QString底层通过Unicode来保存字符串) // "中间"的 utf-8 编码为 : 0xe4,0xb8,0xad,0xe9,0x97,0xb4; char buf[7] = {0}; buf[0] = (char)0xe4; buf[1] = (char)0xb8; buf[2] = (char)0xad; buf[3] = (char)0xe9; buf[4] = (char)0x97; buf[5] = (char)0xb4; QTextCodec *pCodec = QTextCodec::codecForName("utf-8"); QString str = pCodec->toUnicode(buf); //QString str = QTextCodec::toUnicode(barr); //QString QTextCodec::toUnicode ( const char * chars ) const qDebug() << "str : "+str; // "中间"的 gbk 编码为 : 0xd6,0xd0,0xbc,0xe4; memset(buf, 0, sizeof(buf)); buf[0] = (char)0xd6; buf[1] = (char)0xd0; buf[2] = (char)0xbc; buf[3] = (char)0xe4; //QByteArray barr = QByteArray::fromRawData(buf, sizeof(buf)); QTextCodec *pCodec01 = QTextCodec::codecForName("gbk"); QString str01 = pCodec01->toUnicode(buf); //QString str = QTextCodec::toUnicode(barr); //QString QTextCodec::toUnicode ( const char * chars ) const qDebug() << "str01 : "+str01; //*/ } void MainWindow::on_pushButton_2_clicked() { // ZC: 本cpp的默认编码是utf-8的 QString str = "中间"; qDebug() << str; // ZC: 显示"中间"的 utf-8 编码的各个字符 QByteArray barr = str.toUtf8(); for (int i=0; i<barr.length(); i++) { int ii = barr.at(i); ii &= 0xFF; qDebug() << " " << QString::number(ii, 16).leftJustified(2, '0'); } qDebug() << ""; // ZC: 显示"中间"的 gbk 编码的各个字符 QTextCodec *pCodec = QTextCodec::codecForName("gbk"); barr = pCodec->fromUnicode(str); for (int i=0; i<barr.length(); i++) { int ii = barr.at(i); ii &= 0xFF; qDebug() << " " << QString::number(ii, 16).leftJustified(2, '0'); } }
2、
常用函数:
QString QString::fromAscii ( const char * str, int size = -1 ) QString QString::fromLatin1 ( const char * str, int size = -1 ) QString QString::fromLocal8Bit ( const char * str, int size = -1 ) QString QString::fromUtf8 ( const char * str, int size = -1 )
QString QTextCodec::toUnicode ( const char * chars ) const
3、
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
设置QString默认采用的编码。
ZC: 我觉得一般情况下,这个方式还是不要用为妙,省的改来改去 自己都搞不清了...
4、
一般来说就是源代码是GBK,就用GBK,源代码是UTF-8就用UTF-8。但有一个例外,如果你保存成了带BOM的UTF-8而且用的微软的cl编译器,此时仍是GBK。