欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

qt5.5 读写文件的中文乱码解决方案

程序员文章站 2022-03-31 11:41:27
...
#include<QString>
#include<QSetting>

QString localToGBK(QString src)
{
	QString source = src;
	int len = source.length();
	if (len%2 == 1)
		source.append('a');
	QString qstr = QString::fromLocal8Bit(source.toStdString().c_str());
	QString retStr = QTextCodec::codecForName("gbk")->fromUnicode(qstr);
	if (len%2 == 1)
		retStr = retStr.left(retStr.length() -1);
	return retStr;
}

void testIni()
{
	Qstring file = ".\\test.ini";
	Qstring section = "section1";
	{
		QSetting setting(file, QSetting::IniFormat);
		setting.setIniCodec(QTextCodec::codecForName("UTF-8"));
		
		QString s = "中文字符";
		setting.setValue(section1 + "/key", s);
	}
	{
		QSetting setting(file, QSetting::IniFormat);
		setting.setIniCodec(QTextCodec::codecForName("UTF-8"));
		
		QString sKey = setting.value(section + "/key").toString();
		
		QTextStream(stdout << localToGBK(sKey);
	}
}

// 项目配置默认编码UTF-8, 如果编码是UTF-8则添加

相关标签: qt utf8