Qt 中文显示

来源:互联网 发布:mac不能卸载软件 编辑:程序博客网 时间:2024/05/17 01:12

好吧,大家都out啦 Qt5.1(理论上是从Qt5.0开始)更换方法了

以后转换中文就用它对了QStringLiteral("看你妹~");

不要再用tr(),什么的了。


注意:下面方法1, setCodecForTr改为setCodecForCStrings,即可免去tr转换




QT默认的编码(unicode)是不能显示中文的,可能由于windows的默认编码的问题,windows默认使用(GBK/GB2312/GB18030),所以需要来更改QT程序的编码来解决中文显示的问题。

QT中有专门的一个类来处理编码的问题(QTextCodec)。

在QT3中,QApplication可以设置程序的默认编码,但是在QT4中已经没有了该成员函数。
可以以下的这些方法来设置编码。


1. 设置QObject的成员函数tr()的编码。

QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));

其中的codecForName函数是根据参数中的编码名称,在系统已经安装的编码方案中需找最佳的匹配编码类型,该查找是大小写不敏感的。如果没有找到,就返回0。

具体的转换代码看下面:
#include <QApplication>
#include <QTextCodec>
#include <QLabel>


int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
QLabel hello(QObject::tr("你好世界"));
hello.setWindowTitle(QObject::tr("Qt中文显示"));
hello.show();
return app.exec();
}

注意:
setCodecForTr一定要在QApplication后面。不然没有效果。而且这种方法只会转换经过tr函数的字符串,并不转换不经过tr函数的字符串。

技巧:
可以用codecForLocale函数来返回现在系统的默认编码,这样更容易做多编码的程序而不用自己手动来更改具体的编码。


2. 使用QString的fromLocal8Bit()函数

这个方法是最快的,系统直接自动将char *的参数转换成为系统默认的编码,然后返回一个QString。

#include <QApplication>
#include <QTextCodec>
#include <QLabel>


int main(int argc,char *argv[])
{

   QApplication app(argc,argv);

   QString str;
str = str.fromLocal8Bit("Qt中文显示");
hello.setWindowTitle(str);
hello.show();
return app.exec();
}

3. 用QTextCodec的toUnicode方法来显示中文

#include <QApplication>
#include <QTextCodec>
#include <QLabel>


int main(int argc,char *argv[])
{

   QApplication app(argc,argv);
QLabel hello(QObject::tr("你好世界").toLocal8Bit());
QTextCodec *codec = QTextCodec::codecForLocale();
QString a = codec->toUnicode("Qt中文显示");
hello.setWindowTitle(a);
hello.show();
return app.exec();
}

 

PS:关于中文显示乱码的问题我纠结了好久,在网上查的一些方法似乎都不是太管用,所用我自己又实验了很多次,终于解决了这个问题。我其他两种方法我没有试过,我只说第一种方法:

    刚开始的时候我设置QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));或者将"GBK"换成"GB2312","GB18030"都没有成功,依然是乱码。不过也并不是一定不行,后来发现有些时候这样设置也是可以的,我认为可能与源代码的编码方式有关。我后来又找到了一种解决办法就是设置成QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));或者设置成QTextCodec::setCodecForTr(QTextCodec::codecForLocale());我在Ubuntu下,这两种设置都可行;在Windows下,QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));和QTextCodec::setCodecForTr(QTextCodec::codecForLocale());中应该有一种可以,希望我的这些研究能够帮到你。

原创粉丝点击