QT 中文字符乱码

来源:互联网 发布:同轴圆柱形电容器算法 编辑:程序博客网 时间:2024/05/22 12:01

QString –> QByteArray 后字节码与window下的不对。下面的中文字符“中国人民亿”,data是我正常后的GBK字节,value是直接使用
QString ::totoUtf8(),QString ::toLocal8Bit()之类的与期望不符的字节码。

这里写图片描述

首先QString 转换成QByteArray 有三个成员函数

QByteArray QString::toLatin1() constQByteArray QString::toLocal8Bit() constQByteArray QString::toUtf8() const

同样的QByteArray转换成QString 也有对应的

QString::fromLatin1QString::fromLocal8BitQString::fromUtf8

使用Local8Bit转换时,看如下说明

QTextCodec::codecForLocale() is used to perform the conversion from Unicode. If the locale encoding could not be determined, this function does the same as toLatin1().
,所以要想使用local8bit正常转换中文的字节,需要先设置好codecForLocale,可以使用下面的函数设置

[static] void QTextCodec::setCodecForLocale(QTextCodec *c)

示例如下,在main函数中设置中文编码GB18030

int main(int argc, char *argv[]){               QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB18030"));    QApplication a(argc, argv);    MainWindow w;    w.show();    return a.exec();}

然后在使用到中文的地方用tr(“中文字符”),在使用toLocal8Bit时转换就OK了。

    QString str("直接使用");    QByteArray value = str.toLocal8Bit();

方法二 ,直接使用QTextCodec 类

    QString str("直接使用");   QTextCodec *pCodec = QTextCodec::codecForName("GB18030");   QByteArray data = pCodec->fromUnicode(str);       
原创粉丝点击