c++qttranslationqtranslator

How to differentiate between translation did not exist or the translation is the same as source?


I am using QCoreApplication::translate() to translate text.

I am trying to understand whether a string has a translation.

Qt documentation states:

If none of the translation files contain a translation for sourceText in context, this function returns a QString equivalent of sourceText.

The problem I am facing is that I am getting results similar to this:

<message>
    <source>Side</source>
    <translation>Side</translation>
</message>

Where source and translation are the same.

In many languages, the translation is indeed same as the source. But if translate("Side") returns "Side", I can't tell whether the translation was exactly "Side" or whether the translation was empty.

How can I differentiate between the two cases?


Solution

  • AFAIK there is no way to differentiate between the two cases through a QTCoreApplication::translate call.

    However, QTranslator::translate returns a null QString when the key is not found (Qt 5). So one option would be to keep a container around with every QTranslator you've added through installTranslator() (since QCoreApplication doesn't have a way to get those back). Then, loop through that container, calling QTranslator::translate() on each instance in the container. When you get a non-empty result, you found a translation; if no translator succeeded, then you know the key doesn't exist in any QTranslator you have.

    psuedo-code:

    bool hasTranslation(const char* key)
    {
      QString result;
      if(!translators.size())
        return false;
    
      for(const auto& translator : translators)
      {
        result = translator->translate("context", key);
        if(!result.isNull())
          break;
      }
      return !result.isNull();
    }