在动态地动态更改应用程序的语言时,我遇到了一个小问题。
可以从Menu
的{{1}}中选择一种语言,只要我切换到另一种语言,就可以在UI中立即看到更改,除了MenuBar
之外。如果我确实悬停了MenuBar
或调整了窗口的大小,则MenuBar
会更新。
问题出在这里:
我一直试图在QML类型上找到 refresh 函数,但找不到任何函数。
问题
如何确保更改语言后刷新MenuBar
?
修改
这是我的应用程序的完整来源:
main.cpp
MenuBar
Translator.h
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "Translator.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
Translator translator(engine);
engine.rootContext()->setContextProperty("translator", &translator);
return app.exec();
}
Translator.cpp
#ifndef TRANSLATOR_H
#define TRANSLATOR_H
#include <QObject>
#include <QTranslator>
#include <QGuiApplication>
#include <QQmlEngine>
class Translator : public QObject
{
Q_OBJECT
public:
explicit Translator(QQmlEngine &engine, QObject *parent = nullptr);
signals:
void languageChanged();
public slots:
void setLanguage(const QString &language);
private:
QQmlEngine &m_engine;
QTranslator m_trans_fr;
};
#endif // TRANSLATOR_H
main.qml
#include "Translator.h"
Translator::Translator(QQmlEngine &engine, QObject *parent) : QObject(parent),
m_engine(engine)
{
}
void Translator::setLanguage(const QString &language)
{
if (language == QString("fr"))
{
m_trans_fr.load("WipeoutViewer_fr.qm");
qApp->installTranslator(&m_trans_fr);
}
else if (language == QString("en"))
{
qApp->removeTranslator(&m_trans_fr);
}
m_engine.retranslate();
emit languageChanged();
}