1. 程式人生 > 其它 >Qt 國際化,中英文動態切換翻譯實現

Qt 國際化,中英文動態切換翻譯實現

技術標籤:Qt

Qt國際化,使用的是QTranslator類,通過


    QTranslator qtTranslator;
    QString language= "中文";   //顯示語言
    QString dir ;
    if(language != "中文")
    {
        dir = qApp->applicationDirPath() + "/" +"language.eng.qm";
    }
    else
    {
        dir = qApp->applicationDirPath() + "/" +"language.zh_CN.qm";
    }
    if (qtTranslator.load(dir))
    {
        qApp->installTranslator(&qtTranslator);
        qDebug() << "載入語言:installTranslator " << language;
    }

對以上程式碼進行單例化

translator.h

#ifndef TRANSLATOR_H
#define TRANSLATOR_H

#include <QObject>
#include <QWidget>
#include <QSettings>
#include <QTextCodec>
#include <QDir>
#include <QTranslator>
#include <QDebug>
#include <QApplication>

class translator
{
public:
    translator();
    ~translator();
private:
    static translator *curTanslator; //翻譯單例

    QTranslator qtTranslator;
    QString language;   //顯示語言

    void loadTranslator(); //載入翻譯檔案
public:
    static translator *getTranslator();   //獲取翻譯指標

    static void setLanguage(QString lanStr);//設定顯示語言
};

#endif // TRANSLATOR_H

translator.cpp

#include "translator.h"

translator *translator::curTanslator = 0; //翻譯單例
//
translator::translator()
{
    if(curTanslator == 0)
    {
        curTanslator = this;
    }
    QSettings settings(QDir::currentPath()+"/config.ini",QSettings::IniFormat); //讀取配置檔案
    settings.setIniCodec(QTextCodec::codecForName("UTF-8"));
    setLanguage(settings.value("deviceInfo/language","中文").toString());//設定語言
}
//
translator::~translator()
{

}
 //獲取翻譯指標
translator *translator::getTranslator()
{
    if(curTanslator == 0)
    {
        curTanslator = new translator();
    }
    return curTanslator;
}
//載入翻譯檔案
void translator::loadTranslator()
{
    QString dir ;
    if(language != "中文")
    {
        dir = qApp->applicationDirPath() + "/" +"language.eng.qm";
    }
    else
    {
        dir = qApp->applicationDirPath() + "/" +"language.zh_CN.qm";
    }
    if (qtTranslator.load(dir))
    {
        qApp->installTranslator(&qtTranslator);
        qDebug() << "載入語言:installTranslator " << language;
    }
}
//設定顯示語言
void translator::setLanguage(QString lanStr)
{
    if(curTanslator == 0)
        curTanslator = getTranslator();
    if(curTanslator->language != lanStr)
    {
        curTanslator->language = lanStr;
        curTanslator->loadTranslator();
    }
}

使用

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    translator::getTranslator();
    return a.exec();
}

當需要動態切換語言時呼叫介面

translator::setLanguage(language);

同時在各個需要翻譯的類中,重寫


void deviceInfoWidget::changeEvent(QEvent *event)
{
    if(event->type() == QEvent::LanguageChange)
    {
        //翻譯更新介面
        ui->retranslateUi(this);
    }
    else
        QWidget::changeEvent(event);
}