1.TextEdit组件对utf8编码文件的写入和显示
TextEdit组件的setPlainText方法的参数是QString,QString默认是utf8编码。此时无需转码。
写入文件
QFile File(filePath);
QString str=ui->TextEdit->toPlainText();
QByteArray strBytes=str.toUtf8();
File.write(strBytes,strBytes.length());
File.close();
显示文件内容
QFile File(filePath);
QByteArray strBytes = File.readAll();
QString str = strBytes;
ui->TextEdit->setPlainText(str);
File.close;
2.TextEdit组件对gbk编码文件的写入和显示
TextEdit组件的setPlainText方法的参数是QString,QString默认是utf8编码。而用dev编辑的cpp文件则是gbk编码。
所以读取gbk编码的文件并显示到TextEdit上时,要转码;同时将TextEdit上的内容写入gbk编码的文件时,也要转码。否则就会出现乱码。
写入文件
QFile File(filePath);
QString str=ui->TextEdit->toPlainText();
qtc = QTextCodec::codecForName("GBK");
QByteArray strBytes = qtc->fromUnicode(str); //转为ANSI GBK编码
File.write(strBytes,strBytes.length());
File.close();
显示文件内容
QFile File(filePath);
QByteArray strBytes = File.readAll();
qtc=QTextCodec::codecForName("GBK");
QString str = qtc->toUnicode(strBytes); //转为utf8编码
ui->TextEdit->setPlainText(str);
File.close();