单个语言包
标记需要翻译的字符串
Text {
text: qsTr("你好")
}
pro文件添加ts
TRANSLATIONS = zh2en.ts
生成翻译文件
lupdate your_project.pro
用Linguist编辑ts文件进行翻译
生成qm文件
lrelease zh2en.ts
加载qm文件
- 添加qm文件至资源中
- 代码中安装语言包
QTranslator translator;
if (translator.load(":/zh2en.qm")) {
app.installTranslator(&translator);
} else {
spdlog::info("Translation file not loaded!");
}
多个语言包切换
标记字符串
pro文件添加ts
生成多个翻译文件ts
多个语言翻译
加载语言包
例子:中英文切换
- pro文件
QT += quick
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
myobject.cpp
RESOURCES += qml.qrc
TRANSLATIONS = en.ts ch.ts
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
HEADERS += \
myobject.h
- 头文件
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QObject>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QTranslator>
class MyObject : public QObject
{
Q_OBJECT
public:
MyObject(QGuiApplication& app, QQmlApplicationEngine &engine);
Q_INVOKABLE void setEnglish();
Q_INVOKABLE void setChinese();
private:
QGuiApplication *m_app;
QQmlApplicationEngine *m_engine;
QTranslator m_translator;
signals:
};
#endif // MYOBJECT_H
- cpp文件
#include "myobject.h"
#include <QDebug>
MyObject::MyObject(QGuiApplication &app, QQmlApplicationEngine &engine)
{
m_app = &app;
m_engine = &engine;
}
void MyObject::setEnglish()
{
qDebug() << "english";
m_translator.load(":/en.qm");
m_app->installTranslator(&m_translator);
m_engine->retranslate();
}
void MyObject::setChinese()
{
qDebug() << "chinese";
m_translator.load(":/ch.qm");
m_app->installTranslator(&m_translator);
m_engine->retranslate();
}
- qml文件
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.0
Window {
width: 640
height: 480
visible: true
title: qsTr("你好")
Label {
id: lb1
text: qsTr("测试")
}
Button {
id: bt1
anchors.top: lb1.bottom
text: qsTr("设置成中文")
onClicked: {
MyObject.setChinese();
}
}
Button {
id: bt2
anchors.top: lb1.bottom
anchors.left: bt1.right
text: qsTr("设置成英文")
onClicked: {
MyObject.setEnglish();
}
}
}