【Qt开发】Qt中的中文字符问题

来源:互联网 发布:硬件和软件 哪个 编辑:程序博客网 时间:2024/06/05 18:08

之前查了关于处理中文字符的一些资料,说法不一,有些方法又没有效果。只好最终自己尝试了一种适合当前程序的方法。


(1)首先在主函数中重置程序的默认字符编码:

#include <QtGui/QApplication>#include <QTextCodec>#include "mainwindow.h"int main(int argc, char *argv[]){    QApplication a(argc, argv);    //QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());    MainWindow w;    w.show();    return a.exec();}

(其中QTextCodec::codecForLocale()是用来返回系统的默认编码的,另外也可以通过上面注释掉的代码QTextCodec::codecForName("utf8")来指定某一种编码。)


(2)然后,在控件中用到中文字符时,则可以通过QString的toLocal8Bit()或fromLocal8Bit(),来实现const char*与QString之间的转换。

例如要从一个文字编辑框控件取出包含中文的字符串时,可以这样做:

const char* text = ui->sendTextEdit->toPlainText().toLocal8Bit();

而要将包含中文字符的字符串显示在文本框上面时,则可以这样实现:

const char* msg = "信息已发送";

ui->TextEdit->append(QObject::tr(msg));  或  ui->TextEdit->append(QString::fromlocal8bit(msg, strlen(msg)));

原创粉丝点击