QString 中文编码转换

xiaoxiao2021-02-28  113

QT字符编码开发中遇到了很多坑,一不小心就会出现中文乱码, 在这里小结一下。

 QString本身是编码是unicode在windows下local8Bit是GBK  源代码即.cpp文件是有编码的,不同编译器也有默认编码,如: 微软VS的中的cl采用GBKMingw中的g++不带BOM的UTF-8 Linux下的g++ 采用带BOM的UTF-8 这3中编码进行保存

(所以,在代码中hard code中文时, 要搞清楚使用的编译器本身的编码格式)

QString GBK2UTF8(const QString &str) { QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); return utf8->toUnicode(str.toUtf8()); } QString UTF82GBK(const QString &str) { QTextCodec *gbk = QTextCodec::codecForName("GB18030"); return gbk->toUnicode(str.toLocal8Bit()); } std::string GBK2UTF8(std::string &str) { QString temp = QString::fromLocal8Bit(str.c_str()); std::string ret = temp.toUtf8().data(); return ret; } std::string UTF82GBK(std::string &str) { QString temp = QString::fromUtf8(str.c_str()); std::string ret = temp.toLocal8Bit().data(); return ret; }

参考文章:

http://www.cnblogs.com/phoenixlaozhu/articles/2553180.html (这篇写很不错,推荐)

http://blog.csdn.net/ak47zhangzhiwei/article/details/7895422

转载请注明原文地址: https://www.6miu.com/read-45275.html

最新回复(0)