c++qtqlocale

QLocale codeToTerritory only worls with 2-digit codes


I would like to get the Country name for any ISO 3166 country codes. My project currently uses 3-digit codes, so if possible, from that. According to the Qt documentation QLocale::countryToTerritory should solve this, but in my test programs, it only works with 2-digit codes. I also tried the deprecated codeToCountry function, but it has the same result. Also the numeric code does not have any result.

Here is a simple test program:

#include <QCoreApplication>

#include <QLocale>
#include <QDebug>


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString l2 = "DE";
    QString l3 = "DEU";
    QString d3 = "276";

    qDebug() << QLocale::codeToCountry(l2) << QLocale::codeToCountry(l3) << QLocale::codeToCountry(d3);
    qDebug() << QLocale::codeToTerritory(l2) << QLocale::codeToTerritory(l3) << QLocale::codeToTerritory(d3);

    return a.exec();
}

The output is:

QLocale::Germany QLocale::AnyTerritory QLocale::AnyTerritory
QLocale::Germany QLocale::AnyTerritory QLocale::AnyTerritory

I tried with a few different countries, all with the same results.

I built the project with Qt 6.3.0 with MSVC2019 compiler on windows.

Is the documentation simply wrong, or am I missing something?


Solution

  • Looking at the code source of codeToTerritory you can see that the country code is compared against a list of codes contained in territory_code_list. This variable is defined in qlocale_data_p.h.

    It seems that only the ISO 3166-1 alpha-2 code (i.e. 2-character code) is used in this list. There is neither "DEU" nor "276" in territory_code_list, which means that QLocale::AnyTerritory is returned.

    So I do not know if the documentation is wrong, but at least it is imprecise.

    EDIT: digging a bit further, the list of codes is generated from https://unicode.org/Public/cldr/. These files only contain 2-letter codes for countries (there are some 3-digit codes corresponding to continents, but none for countries).

    EDIT2: so, you need to write the conversion from 3-digits / 3-letters code to alpha2-code to be able to use Qt methods. You can get data from this website.