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);
QPushButton hello(QPushButton::tr("Hello world!"));
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.
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);
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.