Qt::中文乱码问题解决

方法一、QTextStream

文件读写时乱码可以用,setAutoDetectUnicode(true) 设置QTextStream可以自动识别Unicode码

cpp 复制代码
bool MainWindow::openTextByStream(const QString &aFileName){
  // 用QTextStream打开文本文件
  QFile aFile(aFileName);
  if (!aFile.exists()) // 文件不存在
  	return false;
  if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    return false;
  QTextStream aStream(&aFile); // 用文本流读取文件
  aStream.setAutoDetectUnicode(true); // 自动检测Unicode
  ui->textEditStream->setPlaintext(aStream.readAll());
  aFile.close(); // 关闭文件
  return true;
}

bool MainWindow::saveTextByStream(const QString &aFileName){
  // 用QTextStream保存文本文件
  QFile aFile(aFileName);
  if(!aFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return false;
  QTextStream aStream(&aFile); // 用文本流读取文件
  aStream.setAutoDetectUnicode(true); // 自动检测Unicode
  QString str = ui->textEditStream->toPlaintext();
  aStream<<str; // 写入文本流
  aFile.close(); // 关闭文件
  return true;
}
方法二、在应用程序中做全局的设置使用UTF-8的编码解码器

文件读写乱码或者其他问题乱码都可以使用此方法,做了全局的设置后读写文件就可以不用setAutoDetectUnicode(true)

cpp 复制代码
int main(int argc, char* argv[]){
  //解决中文乱码问题
  QTextCodec *codec = QTextCodec::codeForName("UTF-8");
  QTextCodec::setCodecForLocale(codec);
  QApplication a(argc, argv);
  MainWindown w;
  w.show();
  return a.exec();
}

对你有用就点个赞👍,以后需要用到就收藏⭐

相关推荐
用户8055336980314 小时前
现代Qt开发教程(新手篇)1.10——进程
c++·qt
vegetablesssss14 小时前
VTK切割图
c++·qt·vtk
Lhan.zzZ16 小时前
笔记_2026.4.28_003
c++·笔记·qt·opencv
m0_6356474816 小时前
Qt打包含有第三方库的软件为应用程序——CQtDeployer
开发语言·数据库·qt
菩提树下的凡夫19 小时前
Qt环境下普通变量与原子变量的区别与联系
qt
小短腿的代码世界1 天前
Qt文件系统与IO深度解析:从QFile到异步文件操作
开发语言·qt
徐某人..1 天前
基于i.MX6ULL平台的智能网关系统开发
arm开发·c++·单片机·qt·物联网·学习·arm
(Charon)1 天前
【C++/Qt】Qt 封装 TCP 客户端底层 Network 类:连接、收发、自动测试与错误处理
服务器·网络·qt·tcp/ip
小短腿的代码世界2 天前
QCefView深度解析:Qt应用中嵌入Chromium浏览器的终极方案
开发语言·qt