QT显示中文

来源:互联网 发布:破解qq悄悄话的软件 编辑:程序博客网 时间:2024/06/05 17:17

常用方法总结如些

1、使用setDefaultCodec进行设置;

  qApp->setDefaultCodec( QTextCodec::codecForName("GBK") );

  QLabel *label = new QLabel( tr("中文标签") );

 可惜setDefaultCodec是QT3的函数,QT4已经不支持了。

2、 设置QObject的成员函数tr()的编码;

   QLabel hello(QObject::tr("你好").toLocal8Bit());

3、使用QString的fromLocal8Bit()函数;

   QString str;

  str = str.fromLocal8Bit("哈哈哈");

  hello.setWindowTitle(str);

4、用QTextCodec的toUnicode方法来显示中文

   QTextCodec *codec = QTextCodec::codecForLocale();

   QString a = codec->toUnicode("安师大手动");

5...

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

  QFont font("Times",12,QFont::Normal,FALSE);

  app.setFont(font);

  ...

  label.setText(QObject::tr("同一个世界,同一个梦想!"));

  ...

6、QTextCodec::codecForName(“GBK”)将返回NULL指针。

   QTextCodec * BianMa = QTextCodec::codecForLocale();   //QTextCodec::codecForName ( "GBK" );

7、

   在QT中可以直接QTextCodec来转换字符串的编码,这为在QT下开发中文软件带来了便利条件,不过这种方  法不符合国际化/本地化的标准:
CODE:
   char *string = "你好,世界!";
   QTextCodec *codec = QTextCodec::codecForName("GBK");
  //QTextCodec *codec = QTextCodec::codecForName("Big5");
  QString strText = codec->toUnicode(string);
  QLabel *label = new QLabel(strText);

最直接的方法是把整个应用程序的编码设置为GBK编码,然后在字符串这前加tr:
CODE:
qApp->setDefaultCodec( QTextCodec::codecForName("GBK") );
...
QLabel *label = new QLabel(tr("你好,世界!"));

8、

使用QStringLiteral()函数

QString str = QStringLiteral("Q:我时常喜欢五颜六色的花朵。3");

 

例:
CODE:
#include
#include
#include <qtextcodec.h>                        //文件头

int main( int argc, char *argv[] )
{
QApplication app( argc, argv );
app.setDefaultCodec( QTextCodec::codecForName("GBK") );
QLabel label(tr("你好,世界!"), NULL);
app.setMainWidget(&label);
label.show();
return app.exec();
}

如果使QT根据Locale的环境变量取得字符集,可以使用如下命令:
QString::fromLocal8Bit("你好,世界!");
例:
CODE:
#include
#include

int main( int argc, char *argv[] )
{
QApplication app( argc, argv );
QLabel label(QString::fromLocal8Bit("你好,世界!"), NULL);
app.setMainWidget(&label);
label.show();
return app.exec();
}
-------------------------------------------------------------------------------------------

法二:

QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
-----------------------------------------------------------------------------------------
法三:可以写个函数
QString   init_gbk(QString s)
{
QGbkCodec* gbk=(QGbkCodec*)QTextCodec::codecForName("GBK");
return gbk->toUnicode(s.latin1(),s.length());
}
调用下就好

 

法9.使用vs2013+Qt5.5.0编译出的程序,发现用上述方法显示中文都是乱码,尝试用以下方法,能够正常显示中文:

在main函数中添加设置本地编码GBK

#include <qtextcodec.h>

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

在遇到中文字符串时,使用QString::fromLocal8Bit(),则能够正常显示中文

QString::fromLocal8Bit(“中文”);

同时使用了此方法后,vs2013编译器提示的字符串末尾有常量编译不过的问题也跟着解决了。


法10,修改cpp文件的文件编码:

将.cpp文件另存为ANSI格式(如不行再各种格式都试一下),再使用法9,就能够正常显示

0 0
原创粉丝点击