根据Qt中的语言更改图标

时间:2015-10-06 13:50:43

标签: qt

是否有一种标准机制可以在Qt中设置依赖于语言的图标。 如果没有,这是否有效,是否安全:

MyWidget->setIcon(QPixmap(dir.currentPath() + tr("/images/icon_en.png") ));
//icon_en should be translated according to corresponding image names

2 个答案:

答案 0 :(得分:1)

根据Qt中的语言环境,没有标准的设置图标的机制。然而,编写自己的机制非常简单。

IMO,在您的代码中使用tr是多余的。这种方式更灵活:

// Get current system locale:
const QString LOCALE = QLocale::system().name(); // For example, result is "en_US"

// Extract language code from the previously obtained locale:
const QString LANG = LOCALE.split('_').at(0);    // Result is "en"

// Path to our icons:
const QString PATH = QString(QApplication::applicationDirPath() + "/images");

// Build the path to the icon file:
const QString ICON = QString("%1/icon_%2.png").arg(PATH, LANG);

// Check if the icon for the current locale exists:
if (QFile::exists(ICON)) {
    // Set this icon for our window:
    setWindowIcon(QPixmap(ICON));
}
else {
    // Otherwise fallback to the default icon:
    setWindowIcon(QPixmap(PATH + "/icon_default.png"));
}

通常,您发布的技术是正确的。您的代码只有几点评论:

答案 1 :(得分:1)

您可以从资源文件中加载图标。

然后,您可以在资源文件中为特定语言指定别名:

<qresource>
    <file>cut.jpg</file>
</qresource>
<qresource lang="fr">
    <file alias="cur.jpg">cut_fr.jpg</file>
<qresource>

这样,当应用程序自动切换为法语时,便会选择别名图标。

相关问题