我在Windows上运行 QT 5.10.1
,app
仅在QML
中生成。我试图在运行时使用新的retranslate()
来更改语言。当前代码可以正常使用附加getEmptyString()
的文本。但qsTr()
中的其余文本却没有。 TranslationHandler.cpp
是空的,我还没有清理包含内容。
因此,我可以使用context属性从QML设置语言。我也检查了引擎是同一个实例。任何想法为什么重新翻译功能不起作用?
感谢您的帮助!
main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QTranslator>
#include <QtGui>
#include <QQmlContext>
#include <QDebug>
#include <QQmlEngine>
#include "translationhandler.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
TranslationHandler transHndl(&engine);
engine.rootContext()->setContextProperty("translateHandler", &transHndl);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
TranslationHandler.h:
#ifndef TRANSLATIONHANDLER_H
#define TRANSLATIONHANDLER_H
#include <QTranslator>
#include <QString>
#include <QGuiApplication>
#include <QObject>
#include <QDebug>
#include <QQmlEngine>
class TranslationHandler : public QObject
{
Q_OBJECT
Q_PROPERTY(QString emptyString READ getEmptyString NOTIFY languageChanged)
public:
explicit TranslationHandler(QQmlEngine *engine)
{
m_translator1 = new QTranslator(this);
m_currentLanguage = "en";
m_engine = engine;
}
QString getEmptyString()
{
return "";
}
Q_INVOKABLE QString getCurrentLanguage()
{
return m_currentLanguage;
}
Q_INVOKABLE void selectLanguage(QString language)
{
if(language == QString("jp"))
{
m_currentLanguage = language;
m_translator1->load(":/translation/qml_jp.qm");
qGuiApp->installTranslator(m_translator1);
m_engine->retranslate();
}
if(language == QString("en"))
{
m_currentLanguage = language;
qGuiApp->removeTranslator(m_translator1);
m_engine->retranslate();
}
emit languageChanged();
}
signals:
void languageChanged();
private:
QTranslator *m_translator1;
QString m_currentLanguage;
QQmlEngine *m_engine;
public slots:
};
#endif // TRANSLATIONHANDLER_H
答案 0 :(得分:0)
这已被确认为错误,将在5.12版中修复。如果您想自己编译,请查看错误报告