qt中文亂碼

解決方法,csdn上看來的,設置爲系統字體,用三個

QTextCodec::setCodecForTr()

QTextCodec::setCodecForCStrings()

QTextCodec::setCodecForLocale()

#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTextCodec>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //Set Encode
    QTextCodec::setCodecForTr(QTextCodec::codecForName("system"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("system"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("system"));

    QDialog w;
    QLabel label(&w);
    label.setText("Hello World!你好,Qt!");   //attention!! 

    w.show();
    return a.exec();
}

另外一種方法,《QT快速入門》一書中的方法,只需要一個set,但是在label中填寫文字的時候,需要

QObject::tr()

QTextCodec類提供了文本編碼的轉換功能。QTextCodec類中的靜態函數setCodecForTr()用來設置

QObject::tr()函數所要使用的字符集。

QTextCodec::codecForLocale()返回了系統指定的字符集,QtextCodec::setCodecForTr()設置tr()用到的字符集。

總之,爲了顯示中文,需要設置字符集,然後使用QObject::tr()函數將字符串進行編碼轉換。

#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTextCodec>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);


    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());  //set
    QDialog w;
    QLabel label(&w);
    label.setText(QObject::tr("Hello World!你好,Qt!"));   //attention!! QObject::tr() used.
    w.show();
    return a.exec();
}


Q:qt的IDE中編寫程序,如上,運行沒問題,但是但是換成直接用command line編譯,代碼是直接拷貝過去的,運行出問題額:

A:後來發現時文件默認編碼問題:

qt直接創建的文件默認編碼爲ANSI
而win7中直接創建文本文件默認編碼爲UTF-8
我把自己創建的文件另存爲ANSI格式之後,再編譯運行,沒有問題了

摘自:

http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece763105392230e54f73a6f8b89462383d60984642c101a39fec0567b4758869e20301cfc090db0ab7225761e26b090c3885dddccd37269d779203541c6171d905fb8cb37669f73c00db7b81996ad814684d8d4c4ae2744ba24127bf0e7fb291764b97886112695a28e49654861bafa4665e828773ee853&p=8f34c116d9c104f900bd9b7d0b1083&newp=9039ca16d9c11bf608e297780b5f97231610db2151d1d51f258d&user=baidu&fm=sc&query=qt+qlabel+%CF%D4%CA%BE%BA%BA%D7%D6%C2%D2%C2%EB&qid=&p1=4

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