You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用QTranslator无法翻译Qt按钮的问题求助

问题:Qt标准GUI元素无法自动翻译(已安装qttranslations包)

我一直使用GNU gettext翻译Python应用,但发现Qt GUI中的标准元素(如QDialogButtonBox.Yes)未被翻译。我查找了QTranslator相关示例,但不确定这是否是正确方案——我本以为Qt会自动识别当前激活的区域设置并完成翻译,比如有类似.use_current_local()的简单开关,但未找到该选项。

我在未完全理解细节的情况下尝试了QTranslator示例代码,代码运行无报错,但按钮仍未翻译。我尝试了三种locale变量值:显式的de_DE.UTF8、QLocale.system().name()返回的de_DE以及qt_de_DE,但均无效。

未翻译的Qt标准按钮

#!/usr/bin/env python3
from PyQt5.QtWidgets import QApplication, QDialogButtonBox
from PyQt5.QtCore import QTranslator, QLocale, QLibraryInfo


def get_translator():
    translator = QTranslator()

    # Variant 1
    loc = QLocale.system().name()

    # Variant 2
    # loc = 'de_DE.utf-8',  # qt_%s' % locale,

    # Variant 3
    # loc = 'qt_de_DE',

    print(f'{loc=}')  # <-- de_DE

    translator.load(
        loc,
        QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    )

    return translator


if __name__ == '__main__':
    app = QApplication([])
    t = get_translator()
    app.installTranslator(t)

    buttonBox = QDialogButtonBox(
        QDialogButtonBox.Ok
        | QDialogButtonBox.Cancel
        | QDialogButtonBox.Yes
        | QDialogButtonBox.No
    )

    buttonBox.show()
    app.exec()

注:我不想用Qt替换现有GNU gettext方案,仅希望Qt标准元素能被翻译,自定义字符串仍通过GNU gettext处理。我使用Debian 12系统,已安装qttranslations5-l10n包,其他Qt应用(如backintime-qt)能正常翻译标准GUI元素。

内容的提问来源于stack exchange,提问作者buhtz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 12:30:08