How to create QLocale from std::locale



  • Is it possible to create a QLocale instance from std::locale?


  • Moderators

    I don't think there's a direct way, but you could probably create it from locale name, i.e.

    std::locale loc = ...
    QLocale qtLoc(QString::fromStdString(loc.name()));
    


  • Hi,

    I had the same idea as Chris, and did this test:

    std::locale stdLocale("");
    QString localeStr = QString::fromStdString(stdLocale.name());
    qDebug() << localeStr;
    // Output: LC_CTYPE=en_US.UTF-8;LC_NUMERIC=fr_FR.UTF-8;LC_TIME=fr_FR.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=fr_FR.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=fr_FR.UTF-8;LC_NAME=fr_FR.UTF-8;LC_ADDRESS=fr_FR.UTF-8;LC_TELEPHONE=fr_FR.UTF-8;LC_MEASUREMENT=fr_FR.UTF-8;LC_IDENTIFICATION=fr_FR.UTF-8
    
    QLocale qLocale(localeStr);
    qDebug() << qLocale;
    // Output: QLocale(C, Default, Default)
    

    So I'm not sure this is the right way to do it.



  • Thanks guys!

    In my case, the std::locale is created with locale( const locale& other, const locale& one, category cat), which constructs a copy of other except for all the facets identified by the cat argument, which are copied from one. If both other and one have names, then the resulting locale also has a name.
    Can it always get correct QLocale to create with locale name?

    If it is impossible to create QLocale exactly same as std::locale, is it possible to create a QLocale instance only with same numeric format with a std::locale instance?



  • @xiazeyi
    I'm no expert in locale, so I don't know if std::locale and QLocale are exactly the same.

    I'm not saying that what Chris and I thought was not the right way to create a QLocale from a std::locale. In fact I don't see any other way to do it, and the documentation, AFAIK, does not provide any information about conversion. I'm only pointing out that you have to test it if you want to be sure that everything works fine. Consult both locale documentations (Qt and std) to create several locales, and print string and numbers from both to compare their outputs.

    http://en.cppreference.com/w/cpp/locale/locale
    http://doc.qt.io/qt-5/qlocale.html

    By the way, may I ask you why you have to convert it instead of using std::locale methods directly?



  • @ValentinMichelet I want to use QIntValidator/QDoubleValidator on Qt GUI.



  • @xiazeyi Do you need to get the default locale? If so, forget about std::locale and create only a QLocale with the static function system():

    QLocale locale(QLocale::system());
    

    Otherwise, if the locale is set by user through the graphical interface, could you output what these values look like?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.