我开始拥有相当不错的软件,但是我想翻译它,所以我在设置菜单中添加了一个组合框。我希望程序在用户在组合框内选择其语言时进行翻译。我已经使用语言学家进行了翻译,并生成了TS和QM文件。我在.pro中链接了ts文件。
main.cpp
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Translator translator(&engine);
engine.rootContext()->setContextProperty("translator", &translator);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
translator.h
class Translator : public QObject
{
Q_OBJECT
Q_PROPERTY(QString emptyString READ getEmptyString NOTIFY languageChanged)
public:
explicit Translator(QQmlEngine *engine)
{
translator = new QTranslator(this);
engine = engine;
}
QString getEmptyString()
{
return "";
}
Q_INVOKABLE void selectLanguage(QString language)
{
if(language == QString("en"))
{
translator->load(":/translation/lang_en.qm");
qGuiApp->installTranslator(translator);
engine->retranslate();
}
if(language == QString("fr"))
{
qGuiApp->removeTranslator(translator);
engine->retranslate();
}
emit languageChanged();
}
signals:
void languageChanged();
private:
QTranslator *translator;
QQmlEngine *engine;
};
main.qml
ComboBox {
id: comboLangage
currentIndex: 0
model: [ qsTr("Français"), qsTr("Anglais") ]
width: 200
onActivated: {
if(comboLangage.currentIndex == 0){
selectLanguage("fr"); // how do i call this method ?
}
else if(comboLangage.currentIndex == 1){
selectLanguage("en")
}
}
}
我尝试使用qmlRegisterType(“ issou.translator”,1,0,“ Translator”);然后将其导入qml。然后,我可以在我的qml中创建一个Translator对象并调用一些函数。但这没有用。有什么建议吗?
谢谢。