1. 程式人生 > 其它 >QT編寫的軟體介面中文亂碼

QT編寫的軟體介面中文亂碼

技術標籤:C/C++

原文連結
https://www.cnblogs.com/sggggr/p/12795591.html

Qt中的中文顯示,經常會出現亂碼。從網上看了一些部落格,大都是Qt4中的解決方法,
網上搜到的都是這種:
複製程式碼

#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()這兩個函式,而且網上很多都是不推薦這種寫法。
我的問題

程式碼:
複製程式碼

#include "helloqt.h"
#include
<QtWidgets/QApplication>
#include <qlabel.h> int main(int argc, char *argv[]) { QApplication a(argc, argv); HelloQt w; w.setWindowTitle("學生事務管理系統"); w.resize(300, 140); QLabel label("test",&w); label.setGeometry(100, 50, 160, 30); w.show();
return a.exec(); }

複製程式碼

結果:
在這裡插入圖片描述

解決方法

有三種轉換的方法:
1.加上#include <qtextcodec.h>
QTextCodec *codec = QTextCodec::codecForName(“GBK”);//修改這兩行
w.setWindowTitle(codec->toUnicode(“學生事務管理系統”));
程式碼改為:
複製程式碼

#include "helloqt.h"
#include <QtWidgets/QApplication>
#include <qlabel.h>
#include <qtextcodec.h>
 
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();
}

複製程式碼

2.w.setWindowTitle(QString::fromLocal8Bit(“學生事務管理系統”));
程式碼改為:
複製程式碼

#include "helloqt.h"
#include <QtWidgets/QApplication>
#include <qlabel.h>
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    HelloQt w;
    w.setWindowTitle(QString::fromLocal8Bit("學生事務管理系統"));//修改這一行
    w.resize(300, 140);
 
    QLabel label("test",&w);
    label.setGeometry(100, 50, 160, 30);
    w.show();
    return a.exec();
}

複製程式碼

3.w.setWindowTitle(QStringLiteral(“學生事務管理系統”));
程式碼改為:
複製程式碼

#include "helloqt.h"
#include <QtWidgets/QApplication>
#include <qlabel.h>
 
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();
}

複製程式碼

結果:
在這裡插入圖片描述

4.在標頭檔案申明中加上

#pragma execution_character_set("utf-8")

一切OK了