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

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

相关推荐
秋田君5 小时前
QT_HTTP协议编程
qt·http·iphone
码农客栈5 小时前
Qt 打包为可执行文件发布
qt
布莱克6051 天前
单例模式详解:什么是单例模式,它能解决哪些问题?
开发语言·qt·单例模式
qq762118221 天前
windows Qt mingw 编译libzip
开发语言·windows·qt
skr爱码士1 天前
10_Qt Designer 与 UI 文件(.ui 原理、uic 编译、动态加载)
c++·qt·ui·客户端
IT爱学堂1 天前
QT原理与源码分析可以学到什么 QT视频课程 QT课程推荐 最新推荐
开发语言·qt
躺着听Jay1 天前
QT交叉编译
开发语言·qt
Quz1 天前
QML 焦点导航:Tab 顺序与方向键移动
qt
程与留1 天前
11_常用控件速查(上):QPushButton、QLabel、QLineEdit、QComboBox
c++·qt
Quz1 天前
QML 按键事件之方向控制
qt