QT默認(rèn)的編碼(unicode)是不能顯示中文的,可能由于windows的默認(rèn)編碼的問(wèn)題,windows默認(rèn)使用(GBK/GB2312/GB18030),所以需要來(lái)更改QT程序的編碼來(lái)解決中文顯示的問(wèn)題。 QT中有專(zhuān)門(mén)的一個(gè)類(lèi)來(lái)處理編碼的問(wèn)題(QTextCodec)。 在QT3中,QApplication可以設(shè)置程序的默認(rèn)編碼,但是在QT4中已經(jīng)沒(méi)有了該成員函數(shù)。 可以以下的這些方法來(lái)設(shè)置編碼。 1. 設(shè)置QObject的成員函數(shù)tr()的編碼。 QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK")); 其中的codecForName函數(shù)是根據(jù)參數(shù)中的編碼名稱(chēng),在系統(tǒng)已經(jīng)安裝的編碼方案中需找最佳的匹配編碼類(lèi)型,該查找是大小寫(xiě)不敏感的。如果沒(méi)有找到,就返回0。 具體的轉(zhuǎn)換代碼看下面: #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后面。不然沒(méi)有效果。而且這種方法只會(huì)轉(zhuǎn)換經(jīng)過(guò)tr函數(shù)的字符串,并不轉(zhuǎn)換不經(jīng)過(guò)tr函數(shù)的字符串。 技巧: 可以用codecForLocale函數(shù)來(lái)返回現(xiàn)在系統(tǒng)的默認(rèn)編碼,這樣更容易做多編碼的程序而不用自己手動(dòng)來(lái)更改具體的編碼。 2. 使用QString的fromLocal8Bit()函數(shù) 這個(gè)方法是最快的,系統(tǒng)直接自動(dòng)將char *的參數(shù)轉(zhuǎn)換成為系統(tǒng)默認(rèn)的編碼,然后返回一個(gè)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方法來(lái)顯示中文 #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(); } PS:關(guān)于中文顯示亂碼的問(wèn)題我糾結(jié)了好久,在網(wǎng)上查的一些方法似乎都不是太管用,所用我自己又實(shí)驗(yàn)了很多次,終于解決了這個(gè)問(wèn)題。我其他兩種方法我沒(méi)有試過(guò),我只說(shuō)第一種方法: 剛開(kāi)始的時(shí)候我設(shè)置QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));或者將"GBK"換成"GB2312","GB18030"都沒(méi)有成功,依然是亂碼。不過(guò)也并不是一定不行,后來(lái)發(fā)現(xiàn)有些時(shí)候這樣設(shè)置也是可以的,我認(rèn)為可能與源代碼的編碼方式有關(guān)。我后來(lái)又找到了一種解決辦法就是設(shè)置成QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));或者設(shè)置成QTextCodec::setCodecForTr(QTextCodec::codecForLocale());我在Ubuntu下,這兩種設(shè)置都可行;在Windows下,QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));和QTextCodec::setCodecForTr(QTextCodec::codecForLocale());中應(yīng)該有一種可以,希望我的這些研究能夠幫到你 |