Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I tried to change locale using QLocale and setDefault function but it seems that it doesn't work. Here is example of changing locale using C localization library and QLocale. For C localization library it seems that it works, but for QLocale it seems that setDefault function call is ignored.

QLocale curLocale(QLocale("pl_PL"));
QLocale::setDefault(curLocale);
QDate date = QDate::currentDate();
QString dateString = date.toString();
// prints "Fri Nov 9 2012" but that was not expected
std::cout << dateString.toStdString() << std::endl;
// prints "en_US", but shouldn't it be "pl_PL"?
std::cout << QLocale::system().name().toStdString() << std::endl;

std::setlocale(LC_ALL, "pl_PL");
// prints "pl_PL"
std::cout << std::setlocale(LC_ALL, 0) << std::endl;
std::time_t currentTime;
std::time(&currentTime);
std::tm* timeinfo = std::localtime(&currentTime);
char charArray[40];
std::strftime(charArray, 40, "%a %b %d %Y", timeinfo);
// prints "pi lis 09 2012" and that's cool
std::cout << charArray << std::endl;

How to change properly locale in Qt so it affects the program?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
455 views
Welcome To Ask or Share your Answers For Others

1 Answer

QLocale::setDefault() does not change the system locale. It changes what QLocale object created with default constructor is.

Supposedly, system locale can only be changed via system control panel/preferences by the user. If you want to format something that is not in the system locale, you need to specifically do that with a locale object.

This code:

QLocale curLocale(QLocale("pl_PL"));
QLocale::setDefault(curLocale);
QDate date = QDate::currentDate();
QString dateString = QLocale().toString(date);
qDebug() << dateString;
qDebug() << QLocale().name();

Prints this:

"pi?tek, 9 listopada 2012" 
"pl_PL" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...