/*
* QTextCodec::codecForLocale()->name() 默认名为 "System"
* 在 Windows 系统上将基于本地区域使用对应的编码
* 中文 Windows 系统一般是 GBK 编码, 中文 Linux 系统一般是 UTF-8 编码
* 为了更好的跨平台,建议在代码中指明 codecForLocale 的编码
* QTextCodec::codecForLocale 的作用有两个
* 1. 指明与外部文件读写的时候使用的默认编码
* 2. 向命令行输出信息(qDebug)使用的编码
*
* const char * 隐式转换为 QString 的过程中, 使用 QTextCodec::codecForCStrings 指定的编码
* 使用 QObject::tr 将 const char * 隐式转换为 QString 的过程中, 使用 QTextCodec::codecForTr 指定的编码
* Qt4.x 默认源文件的编码是 Latin-1
* Qt5.x 默认源文件的编码是 UTF-8
* Qt5.x 已经删除了 QTextCodec::codecForCStrings 和 QTextCodec::codecForTr 函数
*
* // 读取一个UTF-8字符串
* QString utf8_s = QString::fromUtf8("这是一个UTF-8的字符串");
* // 将QString转换为GBK格式的QByteArray字符数组
* // QByteArray::data() 可以返回 const char *
* QByteArray gbk_s = QTextCodec::codecForName("gbk")->fromUnicode(utf8_s);
* // 然后再从GBK字符数组转换回QString
* QString utf8_s2 = QTextCodec::codecForName("gbk")->toUnicode(gbk_s);
*
*/
QTextCodec * codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(codec);
qDebug() << QString::fromUtf8("设置本地系统编码为: %1").arg(QString::fromLatin1(QTextCodec::codecForLocale()->name()));
qDebug() << QString::fromUtf8("提示: 在本地系统编码为 UTF-8 时, QString::fromLocal8Bit 等价于 QString::fromUtf8");
// 用 IODevice 方式打开文本文件
QFile aFile(fileName);
if ( ! aFile.exists() ) { // 文件不存在
return false;
}
if ( ! aFile.open(QIODevice::ReadOnly | QIODevice::Text) ) { // 文件打开失败
return false;
}
ui->textEditDevice->clear();
aFile.seek(0);
// 无法正常打开多字节(ANSI)的中文编码(GBK)文件
// 无法正常打开UTF-16编码的文件
// 只能正常打开UTF-8编码的文件
ui->textEditDevice->setPlainText(QString::fromLocal8Bit(aFile.readAll()));
/*
ui->textEditDevice->clear();
aFile.seek(0);
while ( ! aFile.atEnd() ) {
QByteArray line = aFile.readLine(); // 自动添加 \n
QString str = QString::fromLocal8Bit(line); // 从字节数组转换为字符串
str.truncate(str.length() - 1); // 截断给定索引处的字符串, 去除结尾处的 \n
ui->textEditDevice->appendPlainText(str);
}
*/
aFile.close();
// 用 QTextStream 打开文本文件
QFile aFile(fileName);
if ( ! aFile.exists() ) { // 文件不存在
return false;
}
if ( ! aFile.open(QIODevice::ReadOnly | QIODevice::Text) ) { // 文件打开失败
return false;
}
QTextStream aStream(&aFile); // 用文本流读取文件内容
// 自动检测文件的编码是否存在 UTF-8, UTF-16, or UTF-32 Byte Order Mark (BOM) 并根据检测到的信息选择对应的编码
aStream.setAutoDetectUnicode(true); // 无法正常打开多字节(ANSI)的中文编码(GBK)文件
ui->textEditStream->clear();
aFile.seek(0);
ui->textEditStream->setPlainText(aStream.readAll());
/*
ui->textEditStream->clear();
aFile.seek(0);
while ( ! aStream.atEnd() ) {
QString str = aStream.readLine();
ui->textEditStream->appendPlainText(str);
}
*/
aFile.close();
============= End
原文:https://www.cnblogs.com/lsgxeva/p/12315531.html