1

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!

luffy
  • 2,246
  • 3
  • 22
  • 28
  • 5
    That's why your internal logic cannot rely on manipulating the UI strings. If anything, limit the use of translated strings to the very point where the string is displayed, and use aliases everywhere else throughout your app. – Violet Giraffe Jan 27 '16 at 13:47
  • 3
    Thats why in situation like this you have two values: error text (human readable) and error code (machine readable). Error code is usualy an enum. – Kamil Klimek Jan 27 '16 at 14:01

3 Answers3

2

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

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
2

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
luffy
  • 2,246
  • 3
  • 22
  • 28
  • Just to add: This ... qDebug()<< QCoreApplication::translate ... will not work for unicode on Windows for unicode languages, since qDebug doesn't support unicode strings on this platform. – FourtyTwo Jan 19 '18 at 09:16
0

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.

Thomas
  • 4,980
  • 2
  • 15
  • 30