ot翻译:原始QString文本

Ot translation: original QString text

有没有办法获取标记为翻译的 QString 的原始语言独立文本? 这是我的代码的简化:

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

问题在于:

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

如果用户更改语言将无法正常工作!

MyClass 应该给你错误代码和错误字符串。对于程序逻辑,使用错误代码。对于 UI,使用错误字符串。

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

不,没有。一旦字符串被翻译,它就是一个普通的字符串。

如果您必须使用字符串,那么您的 class 应该 return 未翻译的字符串,并且应该在输出之前进行转换。

错误通常不是字符串,因此该方法可能需要 return 某种错误对象或错误代码。

因此,在进一步阅读文档后,我找到了一个似乎可行的解决方案,并想 post 我的发现以供将来参考:

1) 可以使用以下方式标记要翻译的字符串:QT_TRANSLATE_NOOP(context, text)

2) 要显式获取翻译,请对 C++ 使用 QCoreApplication::translate(),对 QML 使用 qsTranslate()。然后将在定义的上下文中搜索翻译文件以寻找合适的翻译。如果没有找到匹配项,或者没有使用这两个函数,您将返回原始文本。

这里是我在问题中 post 的例子:

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