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

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

相关推荐
笨笨马甲2 小时前
Qt network开发
开发语言·qt
mengzhi啊19 小时前
Qt Designer UI 界面 拖的两个 QLineEdit,想按 Tab 从第一个跳到第二个
qt
笨笨马甲1 天前
Qt MQTT
开发语言·qt
姓刘的哦1 天前
Qt实现蚂蚁线
开发语言·qt
Ivy_belief1 天前
Qt网络编程实战:从零掌握 QUdpSocket 及 UDP 通信
网络·qt·udp
丁劲犇1 天前
在Trae Solo模式下用Qt HttpServer和Concurrent升级MCP服务器绘制6G互联网覆盖区域
服务器·开发语言·qt·ai·6g·mcp·trae
笨笨马甲1 天前
Qt MODBUS协议
开发语言·qt
我喜欢就喜欢1 天前
Word 模板匹配与样式同步技术详解
开发语言·c++·qt·word·模板匹配
Ronin3051 天前
【Qt常用控件】容器类控件和布局管理器
开发语言·qt·常用控件·布局管理器·容器类控件
2301_803554522 天前
qt信号槽机制以及底层实现原理
开发语言·qt