QT5 中文顯示亂碼,編碼用utf-8編碼
阿新 • • 發佈:2019-01-30
QT5 專案中,中文錯誤有兩種方法,分享如下:
1. 就是用utf-8編碼 在 .cpp 中 最上端新增以上程式碼
#pragma execution_character_set("utf-8")
2.使用巨集
QString str = QStringLiteral("我是中文!")
3.使用QString的方法
QString str = QString::fromLocal8Bit("我是中文!");
4.使用編碼
QTextCodec *codec = QTextCodec::codecForName("GB2312");//也可以是GBK QString str = codec->toUnicode("我是中文!");
這裡說一下,以上方法是針對QT5中,中文顯示亂碼的問題,網上針對QT4也有如下的解決辦法
QTextCodec *codec = QTextCodec::codecForName("GBK");
QTextCodec::setCodecForTr(codec);
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
但是QT5中已經取消了setCodecForTr() 與SetCodecForCStrings()函式。我親自試了下,中文依然亂碼。
5.全域性設定
在.pro資料夾中,新建檔案 “charsetsetting.inc”
#pragma execution_character_set("utf-8")
然後再.pro檔案中新增:
win32::QMAKE_CXXFLAGS += -FIcharsetsetting.inc
win32::QMAKE_CFLAGS += -FIcharsetsetting.inc