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.)"
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 viaQLocale::languageToString()andQLocale::countryToString(). Else you only need the language.Granted, that solution would give you
Chinese (Taiwan)rather thanChinese (Traditional)andEnglish (United Kingdom)rather thanEnglish (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, anden_UKwill give you the USA, at least in Qt. Lingering imperialism I guess ;)