现在的位置: 首页 > 综合 > 正文

qt读取中文文件内容的测试

2014年02月20日 ⁄ 综合 ⁄ 共 2571字 ⁄ 字号 评论关闭

qt读取中文文件内容的测试

读取中文文件内容的测试
有3种因素
1文件的编码格式(是utf8格式和非utf8格式)
2程序里面转换得到内容的方式
(QString::fromLocal8Bit 和 codec->toUnicode)
注明一下 这里 QTextCodec*
pcodec = QTextCodec::codecForLocale();
3不同的字体,假设知道有种字体可以正确显示中文这里举例是
Sans Serif字体和 不设置字体
因为我最先考虑的不是字体 所以顺序如下
1.1 不是utf8文件  + QString::fromLocal8Bit  = 方块
1.2 不是utf8文件  +
codec->toUnicode = 乱码
2.1 是utf8文件  + QString::fromLocal8Bit  = 方块
2.2 是utf8文件  +
codec->toUnicode  = 乱码 
上面都没有考虑字体 这时候 热心的网友提醒我注意字体 我就分设置字体和不设置字体
3.1 设置字体 + 不是utf8文件  + QString::fromLocal8Bit = 乱码
3.2 设置字体 +
不是utf8文件  + codec->toUnicode = 乱码
3.3 设置字体 + 是utf8文件  +
codec->toUnicode  = 乱码 
3.4 设置字体 + 是utf8文件  +
QString::fromLocal8Bit  = 终于出来汉字了
设置字体
  QFont font;
  font.setPointSize(16);
   font.setFamily(("Sans
Serif"));
  sceneryInfo->txtLabel->setFont(font);
是utf8文件,这
个要自己用编辑器转
sceneryInfo->txtLabel->setText(QString::fromLocal8Bit(file.readAll()));

字出来了。。。。
不知道我表达清楚了没有呢
QFont font;
font.setPointSize(16);
font.setFamily(("Sans
Serif"));
sceneryInfo->txtLabel->setFont(font);
一定要记得
setPointSize一下哦
    QFile file(strTxt);
    //QTextCodec* pcodec = QTextCodec::codecForName("GBK");
 //QTextCodec*
pcodec = QTextCodec::codecForName("gb18030");
 //QTextCodec* pcodec =
QTextCodec::codecForName("GB2312");
 //QTextCodec* pcodec =
QTextCodec::codecForName("utf8");
 //QTextCodec* pcodec =
QTextCodec::codecForName("ISO 8859-1");
 QTextCodec* pcodec = QTextCodec::codecForLocale();
 if(NULL==pcodec)
 {
  QMessageBox::information(this,tr("notice"),tr("the
textcode is error"));
  return;
 }
 else
 //QTextCodec* pcodec = QTextCodec::codecForLocale();
    if
(file.open(IO_ReadOnly))//QFile::ReadOnly | QFile::Text
 {
  //QTextStream
txtmp(&file);
//设置字体
  QFont font;
  font.setPointSize(16);
   font.setFamily(("Sans
Serif"));
  sceneryInfo->txtLabel->setFont(font);
//QMessageBox::information(this,tr("notice"),QString::fromLocal8Bit("
你好"));//file.readAll() QString::fromLocal8Bit
//pcodec->toUnicode("
你好") 乱码
//QString::fromLocal8Bit("你好") 方块
//QString::fromUtf8("你
好") 也是方块
//使用fromLocal8Bit
  sceneryInfo->txtLabel->setText(QString::fromLocal8Bit(file.readAll()));
//sceneryInfo->txtLabel->setText(QString::fromUtf8(file.readAll()));

//sceneryInfo->txtLabel->setText(pcodec->toUnicode(file.readAll()));
 }
 else
  printf("leedebug
open error/n");
 
 
 
1. 保存中文的文件需要是 unicode 格式.
2. 使用 QString 来保存读取出来的数据(因为QString内部使用的unicode机制,如果你使用 char
那么需要一次转换).
3. 由于很多字体并不支持 全部unicode编码(或者根本不支持unicode编码).那么 unicode
码的中文字还是不能显示的.所以你需要设置 QFont 的 family 是支持中文unicode码的字库.比如 :
宋体(注意:宋体在非windows系统下的具体名称).
   LiuR(8174296) 20:00:06
以上的方法对其他全角字也支持,比如韩文.
   LiuR(8174296) 20:04:17
@leenux:
1. windows下的文本编辑器以 unicode 码保存文件时,采用的是 utf16
的宽字符形式.(有时候可以在windows下编辑好需要的文本文件)
2. QString 的内部编码也是 utf16.
3. QString直接保存 utf16 编码的信息不需要使用QString::fromLocal8Bit 转换就可以成功显示.
 
由于以上因素,我建议文件保存成 utf16 的形式.

抱歉!评论已关闭.