首先确保源文件为UTF-8编码
我用的VS自带的高级保存选项修改,适合项目文件不多的。可以使用一些扩展,但我没学会
点击 工具-自定义,在命令里添加“高级保存选项”
接着一个个打开文件,点击 文件-高级保存选项,选择“UTF-8无签名”,再保存文件就行
尽量将项目属性-高级-字符集,也改成使用 Unicode 字符集
QString转String相互转换
1.代码里中文字符串,控件显示正常,读取文件正常
string Path= "G:/广州_20240620.bin";
//String转QString
QString qstr=QString::fromStdString(Path); //正常
//QString转String
string str=qstr.toStdString(); //正常
//linedit控件显示正常
ui.lineEdit->setText(QString::fromStdString(Path));
//读文件正常
FILE* file;
int openFail = fopen_s(&file, Path.c_str(), "rb");
if (openFail)
return;
2.另一种情况,QXmlStreamReader读取xml
使用toStdString时,控件显示正常,但是读文件失败。
感觉像是QString->乱码,乱码->Qstring,所以显示正常。
//读取xml时,VS调试器会中文乱码,添加监视后在变量名后加上,s8,看着也正常.
QString qstr= reader.readElementText().toStdString();
string Path=qstr.toStdString();
//测试
qDebug() << qstr; //正常
qDebug() << Path.c_str(); //正常
cout<< Path; //乱码
//写入xml也正常
writer.writeTextElement("Path", QString::fromStdString(Path));
//此时linedit控件也显示正常
ui.lineEdit->setText(QString::fromStdString(Path));
//但是读文件会失败
FILE* file;
int openFail = fopen_s(&file, Path.c_str(), "rb");
if (openFail)
return;
此时使用另一种麻烦点的转换方式toLocal8Bit,控件显示正常,读文件正常。
但是有一个问题,就是你用它转换代码里的中文字符串就会乱码!!!个人感觉还没研究透彻…
//读取xml时,VS调试器正常显示
QString qstr= reader.readElementText().toStdString();
string Path= qstr.toLocal8Bit().data();//或者 qstr.toLocal8Bit().toStdString();
//测试
qDebug() << qstr; //正常
qDebug() << Path.c_str(); //乱码
cout<< Path; //正常
//写入xml正常
writer.writeTextElement("Path", QString::fromLocal8Bit(Path.c_str()));
//linedit控件显示正常
ui.lineEdit->setText(QString::fromLocal8Bit(Path.c_str()));
//读文件正常
FILE* file;
int openFail = fopen_s(&file, Path.c_str(), "rb");
if (openFail)
return;
//===================================================
string Path= "G:/广州_20240620.bin";
//String转QString
QString qstr=QString::fromLocal8Bit(Path.c_str()); //乱码,linedit更不用说了
//QString转String
string str=qstr.toLocal8Bit().data(); //乱码
参考链接:
https://blog.csdn.net/m0_59023203/article/details/134937063
https://www.cnblogs.com/lqshang/p/17298205.html