QT 中文字符乱码

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

这里写图片描述

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

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

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

QString::fromLatin1
QString::fromLocal8Bit
QString::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);       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值