1

I have created a QComboBox to list various languages supported in a Qt Application. In order to populate the items in the combo box, I search through all the .qm files for available language codes.

QDir dir(TRANSLATION_PATH);
QStringList file_names = dir.entryList(QStringList("MyApp_*.qm"));
QStringList language_codes;

for (const QString& file_name : file_names) {
    QString code = file_name;             // "MyApp_de.qm"
    code.truncate(code.lastIndexOf('.')); // "MyApp_de"
    code.remove(0, code.indexOf('_') + 1);// "de"
    language_codes.push_back(code);
}

Then I get the language names by constructing a QLocale from the language codes.

for (const QString& language_code : language_codes) {
    QString lang = QLocale::languageToString(QLocale(language_code).language());
    _ui->cboLanguage->addItem(lang, language_code);
}

The problem is that I have languages with the same name zh_CNand zh_TW show up as Chinese, and en_US and en_UK show up as English.

My question is this: Is there a simple, non-brittle way to get the "long" name for these languages? For instance, I would like something like the following if it exists:

QString ui_text = QLocale(language_code).longLanguageName();

// language_code   ->   ui_text
// =============        =======
// "zh_CN"              "Chinese (Simplified)"
// "zh_TW"              "Chinese (Traditional)"
// "en_US"              "English (U.S.)"
// "en_UK"              "English (U.K.)"
Ben Jones
  • 652
  • 6
  • 21
  • There's no country data in your example, only language ("MyApp_de" and not "MyApp_de_DE), so locale is created with `AnyCountry` – Sergei Ousynin Jan 08 '19 at 00:04

1 Answers1

0

You could check if the language code contains a "separator" symbol, either - or _ depending on the format you use, and if so, compose the long string via QLocale::languageToString() and QLocale::countryToString(). Else you only need the language.

Granted, that solution would give you Chinese (Taiwan) rather than Chinese (Traditional) and English (United Kingdom) rather than English (U.K.).

Or you could simply use a map and manually populate it with custom and geopolitically correct entries for the supported languages.

Although the more common practice seems to be to have each language name written in the native language.

Also note that the UK English code is actually en_GB, and en_UK will give you the USA, at least in Qt. Lingering imperialism I guess ;)

dtech
  • 47,916
  • 17
  • 112
  • 190