红联Linux门户
Linux帮助

如何再Qt编程中识别是UTF-8还GBK编码

发布时间:2017-08-11 10:02:40来源:ubuntutouch作者:ubuntutouch
在最近的项目中,我们需要读取在mp3音乐文件中的metadata。如果大家有兴趣的话,可以参阅我的github项目:
https://github.com/liu-xiao-guo/coverinfo
 
我们知道,现在的很多流行的软件都可以去修改一个mp3音乐文件的metadata里的内容,比如再Ubuntu平台上的easytag。当我们存储这些信息的时候,有些人会选取不同的文字编码UTF-8或者是GBK。那么当我们读取这写metadata里的文字时,直接显示,可能会有问题,那么我们怎么来判定是那种编码格式呢?
 
我的解决办法是编写如下的一个方法:
/ The following function will detect whether the strng is encoded in UTF-8 or GBK
QString SongList::getCorrectUnicode(QString input) {
QTextCodec::ConverterState state;
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QString text = codec->toUnicode( input.toLatin1().constData(),
input.toLatin1().size(), &state);
if (state.invalidChars > 0) {
text = QTextCodec::codecForName( "GBK" )->toUnicode(input.toLatin1());
} else {
text = input;
}
return text;
}
 
这个方法的目的是把我们读取的metadata里的文字,通过上面的method来检查字符串是否为一个UTF-8的编码,如果不是,我们直接进行转换为unicode。当然我这样处理只是针对中文的情况。如果需要处理其它国家的文字,我们需要用其它的方法来更一步来处理。
 
本文永久更新地址:http://www.linuxdiyf.com/linux/32286.html