Talk is cheap, Show me the code

0%

Qt+VS中文乱码问题尽可能完全指南

忍受Qt的中文乱码问题很久了,整理了一下避免乱码的方法

建议慎用直接修改编码格式。

  • 很多教程里一上来可能就说设置为”utf-8”就会好,但是也会有很多副作用,比如:
1
2
3
#pragma execution_character_set("utf-8") // 指定字符集,设置前后貌似没发现变化

QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8")); // 这一行也许能暂时解决某个问题,但是会带来更多bug

经测试正常的使用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// 字符串 -> QString
// qDebug以及其他Qt内置函数会强制转换为QString,不做处理则会乱码,建议用fromLocal8Bit提前转换防止中文乱码
qDebug() << QString::fromLocal8Bit("中文输出内容");


/// QString -> char*
char* cstr = qstr.toLocal8Bit().data(); // 通过toLocal8Bit进行转换,表示按照Unicode编码进行转换
// 也可以分两步写
QByteArray temp = qstr.toLocal8Bit();
char *cstr = temp.data(); // 有说法是写一行乱码,分开写不乱码,我测试均正常

/// QString -> std::string
std::string str = std::string(qstr.toLocal8Bit().data()); // 先用toLocal8Bit转为不乱码的char*,再转为std::string
// std::string str = qstr.toStdString(); // 不建议用,这种情况下中文会乱码
-------------The End-------------