新建一个空的Qt项目,然后添加一个一个C++Source File类,名称为main.cpp,添加代码如下:
#include <QApplication>
#include <QDialog>
#include <QLabel>
int main(int argc,char *argv[])
{
QApplication a(argc,argv);
QDialog w;
QLabel label(&w);
label.setText("Hello World!你好Qt!");
w.show();
return a.exec();
}
英文正常显示,中文显示会出现乱码情况如下:
下面添加一些函数让中文正常显示:
#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTextCodec>
int main(int argc,char *argv[])
{
QApplication a(argc,argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
w.resize(200,100);
QLabel label(&w);
label.move(50,50);
label.setText(QObject::tr("Hello World!你好Qt!"));
w.show();
return a.exec();
}
编译运行代码如下:
总结如下,为了可以成功显示中文字符,可以通过如下设置,添加头文件
#include <QTextCodec>
主函数中添加如下代码:
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
label.setText(QObject::tr("Hello World!你好Qt!"));