Qt中文顯示問題解決
Qt中文顯示問題的問題,很多編程人員容易頭疼的問題,小細(xì)節(jié)容易忽略,剛剛編寫好的程序,運行之后可能會出現(xiàn)不顯示或者亂碼這種情況,QT默認(rèn)的編碼(unicode)是不能顯示中文的,可能由于windows的默認(rèn)編碼的問題,windows默認(rèn)使用(GBK/GB2312/GB18030),所以需要來更改QT程序的編碼來解決中文顯示的問題。
QT中有專門的一個類來處理編碼的問題(QTextCodec)。
在QT3中,QApplication可以設(shè)置程序的默認(rèn)編碼,但是在QT4中已經(jīng)沒有了該成員函數(shù)??梢砸韵碌倪@些方法來設(shè)置編碼。
1. 設(shè)置QObject的成員函數(shù)tr()的編碼。
- QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
- Searches all installed QTextCodec objects and returns the one which best matches name; the match is case-insensitive.
- Returns 0 if no codec matching the name name could be found.
其中的codecForName函數(shù)是根據(jù)參數(shù)中的編碼名稱,在系統(tǒng)已經(jīng)安裝的編碼方案中需找***的匹配編碼類型,該查找是大小寫不敏感的。如果沒有找到,就返回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("終于搞定中文"));
- hello.show();
- return app.exec();
- }
注意:
setCodecForTr一定要在QApplication后面。不然沒有效果。而且這種方法只會轉(zhuǎn)換經(jīng)過tr函數(shù)的字符串,并不轉(zhuǎn)換不經(jīng)過tr函數(shù)的字符串。
技巧:
可以用codecForLocale函數(shù)來返回現(xiàn)在系統(tǒng)的默認(rèn)編碼,這樣更容易做多編碼的程序而不用自己手動來更改具體的編碼。
2. 使用QString的fromLocal8Bit()函數(shù)
這個方法是最快的,系統(tǒng)直接自動將char *的參數(shù)轉(zhuǎn)換成為系統(tǒng)默認(rèn)的編碼,然后返回一個QString。
- #include <QApplication>
- #include <QTextCodec>
- #include <QLabel>
- int main(int argc,char *argv[])
- {
- QApplication app(argc,argv);
- // QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
- // QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
- // QLabel hello(QObject::tr("你好"));
- // QLabel hello("你好");
- // hello.setWindowTitle(QObject::tr("終于搞定中文"));
- QString str;
- strstr = str.fromLocal8Bit("哈哈哈");
- 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("安師大手動");
- hello.setWindowTitle(a);
- hello.show();
- return app.exec();
- }
小結(jié):對于Qt中文顯示問題解決,本篇文章介紹完了,這篇文章應(yīng)該對你很有用!希望能幫到你吧!
【編輯推薦】