在 Qt 中更改语言环境

Changing locale in Qt(在 Qt 中更改语言环境)

本文介绍了在 Qt 中更改语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 QLocale 和 setDefault 函数更改语言环境,但似乎不起作用.这是使用 C 本地化库和 QLocale 更改语言环境的示例.对于 C 本地化库,它似乎有效,但对于 QLocale,似乎忽略了 setDefault 函数调用.

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;

如何在 Qt 中正确更改语言环境以影响程序?

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

推荐答案

QLocale::setDefault() 不会更改系统区域设置.它改变了使用默认构造函数创建的 QLocale 对象.

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.

此代码:

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

打印:

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

这篇关于在 Qt 中更改语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Qt 中更改语言环境

基础教程推荐