qt国际化

单个语言包

标记需要翻译的字符串

Text {
    text: qsTr("你好")
}

pro文件添加ts

TRANSLATIONS = zh2en.ts

生成翻译文件

lupdate your_project.pro

用Linguist编辑ts文件进行翻译

生成qm文件

lrelease zh2en.ts

加载qm文件

  1. 添加qm文件至资源中
  2. 代码中安装语言包
QTranslator translator;
if (translator.load(":/zh2en.qm")) {
    app.installTranslator(&translator);
} else {
    spdlog::info("Translation file not loaded!");
}

多个语言包切换

标记字符串

pro文件添加ts

生成多个翻译文件ts

多个语言翻译

加载语言包

例子:中英文切换

  1. 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
  1. 头文件
#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
  1. 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();
}

  1. 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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值