所以,經過進一步的閱讀文檔,我發現,似乎工作的解決方案,並想後我的調查結果以供將來參考:
1)字符串可以使用被標記爲翻譯:QT_TRANSLATE_NOOP(context, text)
2)要明確獲得翻譯,請使用C++的QCoreApplication::translate()
和QML的qsTranslate()
。然後將在定義的上下文中搜索翻譯文件以找到合適的翻譯。如果沒有找到匹配,或者這兩個函數沒有被使用,你會得到原始文本。
這裏我張貼在我的問題的例子:
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
這就是爲什麼你的內在邏輯不能靠操縱UI字符串。如果有的話,將翻譯字符串的使用限制在顯示字符串的位置,並在整個應用程序的其他地方使用別名。 –
這就是爲什麼在這種情況下,你有兩個值:錯誤文本(人類可讀)和錯誤代碼(機器可讀)。錯誤代碼通常是一個枚舉。 –