使用QtCreator新建项目,默认不带UI界面的
编写测试样例,在widget的构造函数中添加一个垂直布局里面添加按钮,按钮显示text
//头文件
#include <QVBoxLayout>
#include <QPushButton>
QPushButton *push=new QPushButton(this);
QVBoxLayout *tmp=new QVBoxLayout(this);
this->setLayout(tmp);
tmp->addWidget(push);
push->setText(tr("text"));
新建翻译文件在文件的text.pro文件里面添加翻译,更新翻译
#对应中文和英文翻译
TRANSLATIONS += zh_text.ts\
en_text.ts
到文件所在文件夹里面找到翻译文件
用Linguist打开,同开两个文件,中文的用中文语言打开,英文的用英文打开,添加选中单词的翻译
点击全部发布
文件夹中会出现出现两个后缀是.qm的文件
程序中添加切换语言的事件,先把语言设置成英文,点击按钮改变为中文语言
//添加头文件
#include <QTranslator>
#include <QApplication>
QTranslator *translator=new QTranslator(this);
translator->load("C:/Users/hebdh/Documents/text/en_text.qm");//路径改为自己项目中en_text.qm所在路径
qApp->installTranslator(translator);
push->setText(tr("text"));
connect(push,&QPushButton::clicked,this,[=](){
translator->load("C:/Users/hebdh/Documents/text/zh_text.qm");//路径改为自己项目中zh_text.qm所在路径
qApp->installTranslator(translator);
push->setText(tr("text"));
});
text.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
TRANSLATIONS += zh_text.ts\
en_text.ts
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
widget.cpp
#include "widget.h"
#include <QVBoxLayout>
#include <QPushButton>
#include <QTranslator>
#include <QApplication>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QPushButton *push=new QPushButton(this);
QVBoxLayout *tmp=new QVBoxLayout(this);
this->setLayout(tmp);
tmp->addWidget(push);
push->setText(tr("text"));
QTranslator *translator=new QTranslator(this);
translator->load("C:/Users/hebdh/Documents/text/en_text.qm");
qApp->installTranslator(translator);
push->setText(tr("text"));
connect(push,&QPushButton::clicked,this,[=](){
translator->load("C:/Users/hebdh/Documents/text/zh_text.qm");
qApp->installTranslator(translator);
push->setText(tr("text"));
});
}
Widget::~Widget()
{
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
};
#endif // WIDGET_H
main文件
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}