Dynamic Qt string translation
If we wrap strings in tr() we can use the linguist to translate qt apps. The following example is one way to dynamically load a language:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTranslator translator;
translator.load("hellotr_la");
app.installTranslator(&translator);
QPushButton hello(QPushButton::tr("Hello world!"));
hello.resize(100, 30);
hello.show();
return app.exec();
}
What I would like to do is is translate to different languages based on say a user preference. The reason is that I'm having a server that needs to handle client requests that has different languages. Having the whole server / process change language via events per request does not feel right. Thus, I'm not interested in the dynamic translation reacting to QEvent::LanguageChange
.
One thing that interested me th开发者_运维知识库us is the following documentation for QCoreApplication::installTranslator()
Multiple translation files can be installed. Translations are searched for in the reverse order in which they were installed, so the most recently installed translation file is searched first and the first translation file installed is searched last. The search stops as soon as a translation containing a matching string is found.
Thus, it seems possible to load multiple languages but my concern then is if I have multiple languages I can not specify which one will be the preferred language. If I have to express in code what I want is something like this:
QString MyApplicationServer::OnHandleRequest(MyRequest &r)
{
//Get the language for this specific request
//For example language can be “hellotr_la” or “hellotr_fr”
// Or another way: "lat", "fra", "enu", "esn" ...
QString language = getLanguageForRequest(r);
//How do I dynamically use language or translate to language?
// This would be the preferred solution.
return tr("Not Implemented", language);
}
If I have to use some custom macros, then so mote it be!
Edit: Basically I would like to get my hands on a specific translated string from the translators.
You don't have to use the provided tr
convenience functions, nor do you have to install the translators. Just look at the API for QTranslator
and you'll see that you can call translate
directly. IF you go this route you can simply have a map of translators available and lookup the text as needed.
If you must use tr
then you have to build a custom translator. Your custom translator can then maintain the map of translators and use a request variable to determine which one to use.
If your server handles only one request at a time then a simple global variable stating the current language would be fine.
Now, if your server handles multiple requests in threads you have a bit more work to do, but not much. In this case you'll store your language preference in a thread local and the installed translator will use that thread local to determine which backing translator to do.
精彩评论