Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing locale in Qt

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?

like image 703
scdmb Avatar asked Nov 09 '12 18:11

scdmb


1 Answers

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" 
like image 199
Stephen Chu Avatar answered Oct 12 '22 08:10

Stephen Chu