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();
}

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

相关推荐
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner2 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz7 天前
QML Hello World 入门示例
qt
xcyxiner10 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner11 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner11 天前
DicomViewer (添加模型类)3
qt
xcyxiner12 天前
DicomViewer (目录调整) 2
qt
xcyxiner12 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能14 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G14 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt