Ot translation: original QString text

859 Views Asked by At

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!

3

There are 3 best solutions below

1
On BEST ANSWER

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
0
On

Is there a way to get the original language independent text of a QString that was marked for translation ?

No there is not. Once the string is translated it is just a regular string.

If you must use strings, then your class should return the untranslated string and the conversion should be do before output.

Errors are usually not strings, so the method might want to return some sort of error object or error code instead.

0
On

MyClass should give you both error codes and error strings. For program logic, use error codes. For UI, use error strings.