Qt輸出中文亂碼,解決方案及自己封裝代碼
Qt中的中文顯示,經常會出現亂碼。網上推薦的方法,我都試過了,很多不管用沒有辦法,有用的又很麻煩,麼有辦法,只好自己封裝了一個類,使用起來方便很多!
使用的時候包含此頭文件即可哦,名字可以自己取!
使用方法舉例:
#include"ShowChinese.h"//自己寫的文件
label = new QLabel(this);
label->setStyleSheet("font-size:20px;color:red");
label->setText(CH("C語言Plus"));
重載了三個函數,你可以使用傳入char*、QByteArray、Qstring直接正常顯示中文,而且寫了一個直接可以設置字符集的函數setTextcodec。
注意:所有函數都是靜態函數,注意使用格式或者直接使用預先定義好的宏函數CH(“你的字符串”)
#pragma once
#include<qstring.h>
#include<qtextcodec.h>
#define CH(str) ShowChinese_tag::ShowChinese(str) //正常顯示中文
typedef class ShowChinese_tag //正常顯示中文的類
{
public:
ShowChinese_tag();
~ShowChinese_tag();
static QString ShowChinese(char *temp);
static QString ShowChinese(QByteArray temp);
//注意:要這樣用-QString temp = QString::fromLocal8Bit("我是中文");
static QString ShowChinese(QString temp);
//設置字符集
static void setTextCodec(char *Charset, int mode = 1);
private:
}gbk,GBK;
QString ShowChinese_tag::ShowChinese(char *temp)
{
QByteArray t(temp);
return QString::fromLocal8Bit(t);
}
QString ShowChinese_tag::ShowChinese(QByteArray temp)
{
return QString::fromLocal8Bit(temp);
}
//注意:要這樣用-QString str2 = QString::fromLocal8Bit("我是中文");
QString ShowChinese_tag::ShowChinese(QString temp)
{
return ShowChinese(temp.toLocal8Bit());
}
//設置字符集,此方式好像沒用
void ShowChinese_tag::setTextCodec(char *Charset,int mode)
{
if (mode == 1)
{
QTextCodec *code = QTextCodec::codecForName(Charset);
QTextCodec::setCodecForLocale(code);
}
else
{
QTextCodec *code = QTextCodec::codecForLocale();
QTextCodec::setCodecForLocale(code);
}
}
ShowChinese_tag::ShowChinese_tag()
{
/*
作者:maye
微信公衆號:C語言Plus(C-P-Plus)
*/
}
ShowChinese_tag::~ShowChinese_tag()
{
/*
感謝使用!
再見!
*/
}