Qt学习之路之解决中文乱码

来源:互联网 发布:电子签名生成器软件 编辑:程序博客网 时间:2024/05/22 13:36

笔者是这样在QT5下解决中乱码的。

1.在需要使用的中文的.cpp文件中, 现在对应的.h文件中添加 头文件: QTextCodec,

2.在 .cpp需要使用中文的函数中添加下面的代码:

QTextCodec *codec = QTextCodec::codecForName("GB18030");
3.接下来就调用 变量 codec的函数 toUnicode()写入中文。

接下来,笔者给出个非常简单的例子。

XXX.h文件

#ifndef CUSTMSGWIDGET_H#define CUSTMSGWIDGET_H#include <QDialog>#include <QPushButton>#include <QLabel>#include <QTextCodec>//---用于解决QT5下中文乱#include <QMessageBox>#include <QGridLayout>#include <QPixmap>#include <QFrame>class CusMsgWidget : public QDialog{Q_OBJECTpublic :explicit CusMsgWidget(QWidget *parent = 0);public slots:void slotShowCustomDlg();private:QPushButton *CustomBtn;QLabel *label;QGridLayout *mainLayout;//---网格布局};#endif//CUSTMSGWIDGET_H

XXX.cpp文件

#include "custmsg_widget.h"CusMsgWidget::CusMsgWidget(QWidget *parent /*= 0*/):QDialog(parent){//---窗口大小resize(200, 100);//-----------------------解决中文乱码QTextCodec *codec = QTextCodec::codecForName("GB18030");//----按钮 与 label 控件CustomBtn = new QPushButton(this);CustomBtn->setText(codec->toUnicode("点击我试试"));label = new QLabel(this);label->setFrameStyle(QFrame :: Panel | QFrame :: Sunken);//-----控件布局mainLayout = new QGridLayout(this);mainLayout->addWidget(CustomBtn, 0, 0);mainLayout->addWidget(label, 1, 0);//---设置事件关联代码connect(CustomBtn, SIGNAL(clicked()), this, SLOT(slotShowCustomDlg()));}//------------槽函数void CusMsgWidget::slotShowCustomDlg(){//-----------------------解决中文乱码QTextCodec *codec = QTextCodec::codecForName("GB18030");//--- label 显示内容label->setText(codec->toUnicode("自定义消息框"));//-QMessageBox 设置标题QMessageBox customMsg;customMsg.setWindowTitle(codec->toUnicode("自定义消息框"));//----设定3个常规按钮QPushButton *yesBtn = customMsg.addButton(codec->toUnicode("是"), QMessageBox::ActionRole);QPushButton *noBtn = customMsg.addButton(codec->toUnicode("否"), QMessageBox::ActionRole);QPushButton *cancelBtn = customMsg.addButton(QMessageBox::Cancel);//---customMsg.setText(codec->toUnicode("这是一个用户自定义的消息框"));customMsg.setIconPixmap(QPixmap(":/1"));customMsg.exec();//-----点击消息框按钮事件处理//--是if (customMsg.clickedButton() == yesBtn){label->setText(codec->toUnicode("点击了自定义消息框的“是”按钮"));}//---否if (customMsg.clickedButton() == noBtn){label->setText(codec->toUnicode("点击了自定义消息框的“否”按钮"));}//---取消if (customMsg.clickedButton() == cancelBtn){label->setText(codec->toUnicode("点击了自定义消息框的“取消”按钮"));}return;}


上面的代码中, 例如这句:

label->setText(codec->toUnicode("自定义消息框"));
这里,setText函数参数类型是QString类型,而调用变量函数toUnicode()

将会返回一个QString类型的变量。相当与下面的代码:

QString labelStr = codec->toUnicode("自定义消息框");label->setText(labelStr);

 

~~~~这样就能完美解决中文乱码了~~~~~





0 0
原创粉丝点击