Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Dynamic multilangual re-evaluation of qml Text in C++ using qsTr() function in qml



  • Hi everyone,

    I would like to know if there is any possibility to use qsTr() or it's functionality in C++ to re-evaluate a qml Text element via C++ instead of the approach suggested in this article when changing the language of the application. http://qt-project.org/wiki/How_to_do_dynamic_translation_in_QML

    The qml text element which gets translated with the according .qm file to different languages.
    @
    Text {
    text: qsTr("Hello World")
    onTextChanged: console.debug(text)
    }
    @

    Somewhere after loading the new language file, I get the according text element and try to translate the new text manually via c++ but in general the textTranslated is never translated correctly! It is always the origin text - because no translation was found.

    @
    // ... loading the new translation file

    if(m_translator->load(languageFile, filePath)) {
        qApp->installTranslator(m_translator);
    }
    
    // ...
    
    QObject *child = children.at(i); // the text element object
    QString textContent = child->property("text").toString();
    QString textTranslated = child->tr(qPrintable(textContent)); // returns textContent
    //QString textTranslated = child->parent()->tr(qPrintable(textContent)); // returns textContent
    //QString textTranslated = m_translator->translate(child->metaObject()->className(),qPrintable(textContent));  // returns ""
    //QString textTranslated = QApplication::translate(child->metaObject()->className(),textContent.toStdString().c_str()); // returns textContent
    qDebug() << "[Translator] text" << qPrintable(textContent) << " of element " << child << textTranslated;
    child->setProperty("text",textTranslated);
    

    @

    The translate functions need a context - which is char* - as first parameter, but I don't really know which content this might be, because I assume the qml object content would be something different.

    I didn't found any implementation of qsTr() neither in the source code nor in the web. It this a real function or only a makro for the Linguist. How does the translation process work anyway?

    Cheers,
    David


Log in to reply