Qt中文顯示

來自 http://lwr0312.blog.163.com/blog/static/483368072010103001811552/

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();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章