QT 中文编码转换

    QByteArray str = msg.toLocal8Bit();
    QTextCodec *gbk = QTextCodec::codecForName("GB18030");
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");
    QString g2u = gbk->toUnicode(str);
    QString as = g2u.toUtf8();            
QTextCodec *gbk = QTextCodec::codecForName("GB18030");
QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");
QString g2u = gbk->toUnicode(m_pUserSpi.m_mapInstruments.find(str1.toStdString())->second->InstrumentName);

QString as = g2u.toUtf8();


头两句是格式。第三句,把括号内查询到的GBK值转成Unicode,第四句把Unicode转成utf-8.

##utf转gbk步骤反过来就行了。

 

    QString tmp =QString::fromLocal8Bit(result["to"].toString().toLocal8Bit().data());
    QString tmp1 =QString::fromLocal8Bit(result["to"].toByteArray().data());
    QString tmp2 =QObject::trUtf8(result["to"].toByteArray().data());
 
 下面分享汇总后的转换代码:(我的环境:neokylin QT4.8.6)
                //Ubuntu firefox http get "我们" %E6%88%91%E4%BB%AC UTF-8
                //Windows ie http get "我们" %CE%D2%C3%C7 GB2312
                char* s="0x我们";   //UTF-8 char*
                QString strT1="0x%CE%D2%C3%C7";  //GB2312的URL百分号编码
                QByteArray baT1,baT2,baT3,baT4;
                PercentEncoding2ByteArray(strT1, baT1);  //自己写的函数,由于QUrl::fromPercentEncoding仅适用UTF-8的URL编码

                strT1=QTextCodec::codecForName("GB2312")->toUnicode(baT1);  //GB2312's QByteArray Convert to QString Unicode
                baT2=QTextCodec::codecForName("GB2312")->fromUnicode(strT1);    //QString Unicode convert to GB2312 QByteArray
                QString strT2,strT3,strT4,strT5;
                strT2=QTextCodec::codecForName("UTF-8")->toUnicode("0x我们"); //UTF-8 Char* to Unicode QString
                baT3=QTextCodec::codecForName("UTF-8")->fromUnicode(strT2);     //Unicode QString to UTF-8 QByteArray
                strT3=QTextCodec::codecForName("UTF-8")->toUnicode(s); //UTF-8 Char* to Unicode QString
                strT4=QUrl::toPercentEncoding(QString::fromLocal8Bit(s));   //UTF-8 Char* to PercentEncoding (UTF-8 format)
                strT5=QUrl::fromPercentEncoding("0x%E6%88%91%E4%BB%AC");    //PercentEncoding (UTF-8 format) to Unicode

                baT4=QTextCodec::codecForName("GB2312")->fromUnicode(QTextCodec::codecForName("UTF-8")->toUnicode(s));  //UTF-8 Char* to GB2312 QByteArray

另附一个小函数:(用于GB2312的URL百分号编码转换)
    void PercentEncoding2ByteArray(QString strInput, QByteArray & ByteArrayOut)
    {
        for(int i=0; i

你可能感兴趣的:(Linux,VC++)