Qt界面显示中文乱码问题

来源:互联网 发布:除了京东淘宝还有什么 编辑:程序博客网 时间:2024/06/05 23:04

Qt界面显示中文乱码问题

发表于2年前(2013-06-20 15:12)   阅读(3372) | 评论(0) 2人收藏此文章, 我要收藏
0

8月22日珠海 OSC 源创会正在报名,送机械键盘和开源无码内裤  

QT
http://my.oschina.net/zjlaobusi/blog/138983

解决方法,csdn上看来的,设置为系统字体,用三个

QTextCodec::setCodecForTr()

QTextCodec::setCodecForCStrings()

QTextCodec::setCodecForLocale()

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTextCodec>
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 
    //Set Encode
    QTextCodec::setCodecForTr(QTextCodec::codecForName("system"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("system"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("system"));
 
    QDialog w;
    QLabel label(&w);
    label.setText("Hello World!你好,Qt!");   //attention!! 
 
    w.show();
    return a.exec();
}

另外一种方法,《QT快速入门》一书中的方法,只需要一个set,但是在label中填写文字的时候,需要

QObject::tr()

QTextCodec类提供了文本编码的转换功能。

QTextCodec类中的静态函数setCodecForTr()用来设置QObject::tr()函数所要使用的字符集。

QTextCodec::codecForLocale()返回了系统指定的字符集,QtextCodec::setCodecForTr()设置tr()用到的字符集。


总之,为了显示中文,需要设置字符集,然后使用QObject::tr()函数将字符串进行编码转换。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTextCodec>
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 
 
    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());  //set
    //or the code below may work, not the same as the book told in P27
    //replace "UTF-8" with "GB2312"
    //QTextCodec::setCodecForTr(QTextCodec::codecForTheName("GB2312"));
    QDialog w;
    QLabel label(&w);
    label.setText(QObject::tr("Hello World!你好,Qt!"));   //attention!! QObject::tr() used.
    w.show();
    return a.exec();
}


Q:在qt的IDE中编写程序,如上,运行没问题,但是但是换成直接用command line编译,代码是直接拷贝过去的,运行出问题额:

A:后来发现时文件默认编码问题:

如果文件中有中文,则需要存储为UTF-8的格式,比如用IDE根据模板生成的示例工程2-1,

文件编码hellodialog.cppANSIhellodialog.hANSIhellodialog.uiUTF-8helloworld.proANSIhelloworld.pro.userANSImain.cppANSI

只有在界面当中直接输入了中文“Hello world!你好,Qt!",因此只有“hellodialog.ui”这个文件是“UTF-8格式”的。

而在范例2中(2-2),由于需要手动输入中文,故只有文件“main.cpp”的编码是“UTF-8”的。

 helloworld.proANSIhelloworld.pro.userANSImain.cppUTF-8


用qt直接创建的文件默认编码为ANSI,中文则为UTF-8
而win7中直接创建文本文件默认编码为ANSI
我把自己创建的文件另存为UTF-8格式之后,再编译运行,没有问题了

编码问题参考:http://bbs.chinaunix.net/thread-753836-1-1.html

0 0