Canonical QTranslator example with real-world QLocale

336 Views Asked by At

It seems that most documentation on QTranslator and installing them for a QApplication assume simplistic cases for QLocale.

In the real-world the locale of the user must take into account language and country, which is commonly achieved by having translation files first for a language (en) and then additional translation files for each country using that language (en_US).

Using the default QLocale(), what is the most elegant way to load the appropriate translation files (one, two or none, depending on which exist)?

Here some code that get's it right, but is a bit too cumbersome.

1

There are 1 best solutions below

0
On
bool Application::installTranslator(QString localeName)
{
  QTranslator* translator = new QTranslator(this);

  QString fileToLoad = ":/translators/translation_" + localeName + ".qm";

  if (!QFile::exists(fileToLoad))
    return;

  if (translator->load(fileToLoad)) // Caution this will perform stripping of '_' heuristic
    QApplication::installTranslator(translator);
}

void Application::installTranslator()
{
  QLocale locale;
  boost::optional<QString> optLanguage = m_commandLineParser->getLanguage();
  if (optLanguage)
    locale = QLocale(optLanguage.get());

  // Load language (en, de, etc.) translator first
  QString language = locale.name().left(2);
  installTranslator(language);

  // Load country translator (en_US, de_CH, etc.) translator second
  installTranslator(locale.name());
}