c++qtqt-linguist

Ot translation: original QString text


Is there a way to get the original language independent text of a QString that was marked for translation ? Here is a simplification of my code:

QString MyClass::getError()
{
   QString errorText = tr("hardError1");
   return errorText;
}

The problem is that the following:

if (getError().contains("hard"))
{
//do something
}

will not work properly if the user changes the language!


Solution

  • So after further reading the documentation I found a solution that seems to work, and wanted to post my findings for future reference:

    1) Strings can be marked for translation using: QT_TRANSLATE_NOOP(context, text)

    2) To explicitly get the translation use QCoreApplication::translate() for c++ and qsTranslate() for QML. The translation files will then be searched for a suitable translation within a defined context. If no match was found, or those two functions were not used, you will get the original text back.

    Here the example I posted in my question:

    QString MyClass::getError()
    {
       QString errorText = QT_TRANSLATE_NOOP("errorContex", "hardError1");
       return errorText;
    }
    
    qDebug()<< getError(); //this will give you the original string
    qDebug()<< QCoreApplication::translate("errorContex", getError()); //this will give you the translation of the string according to the set language
    
    console.log(qsTranslate("errorContex", myclass.getError())) //this will give you the translation of the string in QML