nokia Qt支持中文方法

December 9, 2009 – 7:37 pm

参考网络上的资源,总结的一个解决Qt中文支持的方法,还没有仔细深究,暂时记录在这里,当模板使用。
编写一个最简单的Qt程序,参考教材《C++ GUI Qt4编程 第二版》,编译。

  1. #include <QtGui/QApplication>
  2. #include <qlabel.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6.     QApplication a(argc, argv);
  7.  
  8.     QLabel *label = new QLabel("hello nokia Qt");
  9.     label->show();
  10.     return a.exec();
  11. }

编译通过,如图:
nokia Qt hello world in English
这还不够,我们要做的程序必须支持中文,改写一下。

  1. #include <QtGui/QApplication>
  2. #include <qlabel.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6.     QApplication a(argc, argv);
  7.  
  8.     QLabel *label = new QLabel("hello 诺基亚 Qt");
  9.     label->show();
  10.     return a.exec();
  11. }

结果就出现问题了,nokia Qt支持中文有问题,如图:
nokia Qt hello world in cn wrong
怎么办呢,继续修改代码,再次编译

  1. #include <QtGui/QApplication>
  2. #include "dialog.h"
  3. #include <qlabel.h>
  4. #include <qtextcodec.h>
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8.     QApplication a(argc, argv);
  9.  
  10.     QTextCodec *codec = QTextCodec::codecForName("utf8");
  11.     QTextCodec::setCodecForLocale(codec);
  12.     QTextCodec::setCodecForCStrings(codec);
  13.     QTextCodec::setCodecForTr(codec);
  14.  
  15.     QLabel *label = new QLabel("hello 诺基亚 Qt");
  16.     label->show();
  17.     return a.exec();
  18. }

成功,如图:
nokia Qt hello world in cn right

  1. One Response to “nokia Qt支持中文方法”

  2. 很好,非常详细了,!谢谢大哥!

    By 互动投影 on Apr 26, 2010

Post a Comment