Mendes
Mendes

Reputation: 18451

QML translator error: only works if I add a translator.emptyString after qsTr

Using QML on Qt, I've setup up my QML Translator (called translator).

Running that code:

Text {
     id: title
     text: qsTr("title") + translator.emptyString
}

I get the translated message ("Whatever message")

Running this code:

Text {
     id: title
     text: qsTr("title")
}

I get no translation ("title" printed)

Why do I need the emptyString stuff? How to make it work normally (without the emptyString) ?

My translator:

#include "translator.h"
#include <QDebug>
#include <QGuiApplication>
#include <QDir>

Translator::Translator()
{
    translator = new QTranslator(this);
}

QString Translator::getEmptyString()
{
    return QString();
}

void Translator::selectLanguage(QString language)
{
    if (!translator->load(
            // for example, in case of "pt" language the file would be
            // qedgeui_pt.qm
            // extension is set automatically
            QString("ui_%1").arg(language), ":/i18n"
            )
        )
    {
        qDebug() << "Failed to load translation for " << language;
    }
    else {
        qDebug() << "Translator language" << language << "loaded: " << QString("ui_%1").arg(language) << ":/i18n";
    }
    // it's a global thing, we can use it anywhere (after #including <QGuiApplication>)
    if (!qApp->installTranslator(translator))
    {
        qDebug() << "Failed to install translation for " << language;
    }

    emit languageChanged();
}

And in main:

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "translator.h"

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;

    Translator translator;

    auto context = engine.rootContext();
    context->setContextProperty("translator", &translator);

    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.selectLanguage("en");
    qDebug() <<  QApplication::translate("Header", "title", 0); // Works fine here


    return app.exec();
}

Upvotes: 0

Views: 41

Answers (1)

Amfasis
Amfasis

Reputation: 4168

Since you have changed the language after loading the qml, you will need to let the qml engine know it needs to apply the translations again: https://doc.qt.io/qt-6/qqmlengine.html#retranslate

you will have to get hold of a reference/pointer to qmlEngine in your code, but possibly this works:

auto *eng = qmlEngine(parent());
if(eng)
    eng->retranslate();

Upvotes: 1

Related Questions