QT中的中文显示问题
来源:互联网 发布:权限数据库设计面试题 编辑:程序博客网 时间:2024/06/10 04:47
原文出处
QT中的中文显示问题
QT默认的编码(unicode)是不能显示中文的,可能由于windows的默认编码的问题,windows默认使用(GBK/GB2312/GB18030),所以需要来更改QT程序的编码来解决中文显示的问题。
QT中有专门的一个类来处理编码的问题(QTextCodec)。
在QT3中,QApplication可以设置程序的默认编码,但是在QT4中已经没有了该成员函数。
可以以下的这些方法来设置编码。
1. 设置QObject的成员函数tr()的编码。
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
Searches all installed QTextCodec objects and returns the one which best matches name; the match is case-insensitive. Returns 0 if no codec matching the name name could be found.
其中的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("终于搞定中文"));
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);
// QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
// QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
// QLabel hello(QObject::tr("你好"));
// QLabel hello("你好");
// hello.setWindowTitle(QObject::tr("终于搞定中文"));
QString str;
str = str.fromLocal8Bit("哈哈哈");
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("安师大手动");
hello.setWindowTitle(a);
hello.show();
return app.exec();
}
- QT中的中文显示问题
- QT中文显示问题
- Qt 中文显示问题
- QT中文显示问题
- QT中文显示问题
- QT中文显示问题
- QT显示中文的问题
- QT 中文显示的问题
- QT中文显示的问题
- Qt+Mysql中文显示问题
- 关于Qt中文显示问题
- QT中文显示问题(转载)
- 【Qt开发】Qt中的中文字符问题
- PyQt4中的中文显示问题
- iText7中的中文显示问题
- J2ME中的中文显示问题
- Qt显示中文的问题详解
- QT在linux下中文显示问题
- 关于CLS,CTS,CLI
- 托管与非托管
- 部署和分发.NET应用程序的两种方法
- RIP V1 的发送和接收规则(
- 《Refactoring to patterns》
- QT中的中文显示问题
- 图解冲突域、广播域
- 正则表达式验证代码(字母、数字、Email、网址、电话号码、汉字、身份证号码)
- 听力完全攻略
- 听力完全突破法
- 默认参数在哪指定?函数声明还是定义?
- "stdafx.h"是起什么作用的?
- 无法为数据库中的对象分配空间
- MSE、工程/工学硕士、学历/学位、单双证终极解释