Qt中文显示乱码解决方法 | 您所在的位置:网站首页 › qt设置窗口标题乱码 › Qt中文显示乱码解决方法 |
Qt中文显示乱码解决方法 一、Qt4中的解决方法 方法1:在程序开始时增加初始编码类型 #include < QTextCodec > int main(int argc, char **argv) { .................... QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF8")); QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF8")); .......................... } Qt5中, 取消了QTextCodec::setCodecForTr()和QTextCodec::setCodecForCString()这两个函数,而且网上很多都是不推荐这种写法。 方法2:直接转换 加上#include QTextCodec *codec = QTextCodec::codecForName("GBK");//修改这两行 w.setWindowTitle(codec->toUnicode("中文按钮")); 完整代码: #include "helloqt.h" #include #include #include int main(int argc, char *argv[]) { QApplication a(argc, argv); HelloQt w; QTextCodec *codec = QTextCodec::codecForName("GBK"); w.setWindowTitle(codec->toUnicode("中文按钮")); w.resize(300, 140); QLabel label("test",&w); label.setGeometry(100, 50, 160, 30); w.show(); return a.exec(); }二、Qt5中的解决方法 方法1:先将对应的cpp文件用windows自带的记事本打开,另存为UTF-8格式,然后在代码中,遇到中文字符,使用QStringLiteral("中文")进行修饰。这种方式每次新建一个class就要切出去用记事本编辑一下实在麻烦,而且每个中文字符串都要用QStringLiteral来修饰,实在麻烦。 #include "helloqt.h" #include #include int main(int argc, char *argv[]) { QApplication a(argc, argv); HelloQt w; w.setWindowTitle(QStringLiteral("中文按钮")); w.resize(300, 140); QLabel label("test",&w); label.setGeometry(100, 50, 160, 30); w.show(); return a.exec(); }方法2:在头文件申明中加上 #pragma execution_character_set("utf-8") 方法3:直接转换 加上#include QTextCodec *codec = QTextCodec::codecForName("GBK");//修改这两行 w.setWindowTitle(codec->toUnicode("中文按钮")); |
CopyRight 2018-2019 实验室设备网 版权所有 |