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()
{
/*
感谢使用!
再见!
*/
}