Qt中文编码和QString类Unicode编码转换

转自https://blog.csdn.net/g423tgl234/article/details/52222569

1 window中文GBK编码和Unicode编码转换

    //GBK‐> QString
    QString str = QString::fromLocal8Bit("新浪微博");

     
    //QString ‐> GBK
    QString text = ui.lineEdit‐>text();
    QByteArray bytes = text.toLocal8Bit();
    const char* gbk = bytes.data();


2 Linux中文中文编码和Unicode编码转换

    UTF‐8‐> QString :
    char utf8[] = {0xE4 ,0xBD, 0xA0, 0xE5, 0xA5, 0xBD, 0};   
    QString str2 = QString::fromUtf8(utf8);

     
    QString ‐> UTF‐8:
    QString text = ui.lineEdit‐>text();
    QByteArray bytes = text.toUtf8();
    const char* utf8 = bytes.data();
    int size = bytes.size();
     

    3 使用QTextCodec类实现编码

// QString(Unicode) ‐> std::string (GBK)
    static string FromUnicode(const QString& qstr)
    {
    QTextCodec* pCodec = QTextCodec::codecForName("gb2312");
    if(!pCodec) return "";
    QByteArray arr = pCodec‐>fromUnicode(qstr);
    string cstr = arr.data();
    return cstr;
    }

    // std::string (GBK) ‐> QString(Unicode)
    static QString ToUnicode(const string& cstr)
    {
    QTextCodec* pCodec = QTextCodec::codecForName("gb2312");
    if(!pCodec) return "";
    QString qstr = pCodec‐>toUnicode(cstr.c_str(), cstr.length());
    return qstr;
    }
 

你可能感兴趣的:(Qt)