背景:
多个子项目,分别翻译生成的qm文件,如何一键加载?
.h
#include <QtCore/QObject>
#include <QtCore/QTranslator>class LanguageSelector:public QObeject{Q_OBJECT
public:~LanguageSelector() override = default;void setLanguage(const QString &l);QString getLanguage();void addLanguageFile(const QString &n);void removeLanguageFile(const QString &n);void reload();static LanguageSelector *getInstance();
signals:void languageChanged(const QString &l);
privite:LanguageSelector();static LanguageSelector* instance;static constexpr char CONFIGER_KEY[] = "system/language";QString baseDir;QList<QString> languageFiles;QList<QTranslator *> translations;
}
.cpp
#include "languageselector.h" #include <QApplication> #include <QCoreApplication> #include <QDebug> #include <QStringBuilder> #include <QSettings>LanguageSelector *LanguageSelector::instance = nullptr; constexpr char LanguageSelector::CONFIGER_KEY[]; QString LanguageSelector::getLanguage() {return QSettings::value( CONFIGER_KEY, defaultValue ); }void LanguageSelector::setLanguage(const QString &language) {QSettings qs;auto ov = QSettings::value( CONFIGER_KEY, defaultValue );qs::setValue( CONFIGER_KEY, language);if(ov != l){reload();emit languageChanged( language);} }LanguageSelector *LanguageSelector::getInstance() {if(!instance){instance = new LanguageSelector;}return instance; }LanguageSelector::LanguageSelector(): baseDir( "i18n" ) {}void LanguageSelector::addLanguageFile(const QString &name) {if(name.isEmpty()){return;}languageFiles.append(name); }void LanguageSelector::removeLanguageFile(const QString &name) {if(name.isEmpty()){return;}languageFiles.removeOne(name); }void LanguageSelector::reload() {auto language = getLanguage();QString qmBase = QApplication::applicationDirPath() + "/" + baseDir;if(!qmBase.isEmpty() && !qmBase.endWith("/")){qmBase += "/";}if(!translations.isEmpty()){for(auto const t : translations){QCoreApplication::removeTranslator(t);t->deleteLater();}}for(auto const &qm :languageFiles){auto *t = new QTranslator(this);if(t->load(qmBase % qm % "_" % language ))translations.append(t);QCoreApplication::installTranslator(t);}else{qDebug() << "can not load lang file:" << qm << ", language" << language ;} }
使用:
main中,节目构造之前添加:
auto ls = LanguageSelector::getInstance();ls->addLangFile( "test" );ls->addLangFile( "local" );ls->addLangFile( "remote" );ls->reload();