Qt中文乱码解决

一、Qt代码文件格式设置为UTF8

1、std::cout乱码处理

    std::cout << QString::fromUtf8("你好").toLocal8Bit().data() << std::endl;

2、文件名称乱码处理

    QFile file(QString("你好.csv").toUtf8());

3、文件数据乱码处理

    //必须分两步转换

    QByteArray msgByteArray = QString::fromUtf8("你好,Qt:我爱你!__##").toLocal8Bit();

    const char* msg = msgByteArray.data();

    file.write(msg, strlen(msg));

保存的数据文件内容字符集格式为ANSI(Windows),CSV文件在Excel中打开需要使用ANSI字符集编码。

    //必须分两步转换

    QByteArray msgByteArray = QString::fromUtf8("你好,Qt:我爱你!__##").toUtf8();

    const char* msg = msgByteArray.data();

    file.write(msg, strlen(msg));

保存的数据文件内容字符集格式为UTF8。

完整代码

#include <iostream>
#include <QFile>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    std::cout << QString::fromUtf8("你好").toLocal8Bit().data() << std::endl;
    QFile file(QString("你好.csv").toUtf8());
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    //必须分两步转换
//    QByteArray msgByteArray = QString::fromUtf8("你好,Qt:我爱你!__##%1").arg(100).toUtf8();//文件数据编码格式UTF8
    QByteArray msgByteArray = QString::fromUtf8("你好,Qt:我爱你!__##%1").arg(100).toLocal8Bit();//文件数据编码格式ANSI(Windows)
    const char* msg = msgByteArray.data();
    file.write(msg, strlen(msg));
    file.close();
    return a.exec();
}

二、Qt代码文件格式设置为GBK

1、std::cout乱码处理

    std::cout << QString::fromLocal8Bit("你好").toLocal8Bit().data() << std::endl;

2、文件名称乱码处理

    QFile file(QString::fromLocal8Bit("你好.csv").toUtf8());

3、文件数据乱码处理

    //必须分两步转换

    QByteArray msgByteArray = QString::fromLocal8Bit("你好,Qt:我爱你!__##").toLocal8Bit();

    const char* msg = msgByteArray.data();

    file.write(msg, strlen(msg));

保存的数据文件内容字符集格式为ANSI(Windows),CSV文件在Excel中打开需要使用ANSI字符集编码。

    //必须分两步转换

    QByteArray msgByteArray = QString::fromLocal8Bit("你好,Qt:我爱你!__##").toUtf8();

    const char* msg = msgByteArray.data();

    file.write(msg, strlen(msg));

保存的数据文件内容字符集格式为UTF8。

完整代码

#include <iostream>
#include <QFile>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    std::cout << QString::fromLocal8Bit("你好").toLocal8Bit().data() << std::endl;
    QFile file(QString::fromLocal8Bit("你好.csv").toUtf8());
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    //必须分两步转换
//    QByteArray msgByteArray = QString::fromLocal8Bit("你好,Qt:我爱你!__##%1").arg(100).toUtf8();//文件数据编码格式UTF8
    QByteArray msgByteArray = QString::fromLocal8Bit("你好,Qt:我爱你!__##%1").arg(100).toLocal8Bit();//文件数据编码格式ANSI(Windows)
    const char* msg = msgByteArray.data();
    file.write(msg, strlen(msg));
    file.close();
    return a.exec();
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值