上下文菜单没有使用PyQt5显示正确的语言

时间:2018-01-08 20:46:01

标签: python qt pyqt pyqt5

当我尝试使用PyQt5创建Qt应用程序时,我注意到QPlainTextEdit标准上下文菜单是用英语显示的,这不是我的系统语言(葡萄牙语),尽管它的语言环境是从其父窗口小部件正确继承的。这是预期的行为吗?如果是这样,我如何添加翻译而不必重写该上下文菜单中已存在的功能(如剪切/复制/粘贴)?

实施例

该程序再现了上述行为;它显示一个窗口(因此textEditor.locale().language()具有与QLocale.Portuguese相同的值),但上下文菜单以英语显示。

import sys
from PyQt5.QtWidgets import QApplication, QPlainTextEdit, QMainWindow
from PyQt5.QtCore import QLocale

def main():
    app = QApplication(sys.argv)

    window = QMainWindow()  

    assert(window.locale().language() == QLocale.Portuguese)    
    textEditor = QPlainTextEdit(window)

    assert(textEditor.locale().language() == QLocale.Portuguese)
    window.setCentralWidget(textEditor)
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

您需要安装QTranslator来添加系统区域设置的翻译。

import sys
from PyQt5.QtWidgets import QApplication, QPlainTextEdit, QMainWindow
from PyQt5.QtCore import QLocale, QTranslator, QLibraryInfo

def main():
    app = QApplication(sys.argv)

    # Install provided system translations for current locale
    translator = QTranslator()
    translator.load('qt_' + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(translator)

    window = QMainWindow()

    assert(window.locale().language() == QLocale.Portuguese)
    textEditor = QPlainTextEdit(window)

    assert(textEditor.locale().language() == QLocale.Portuguese)
    window.setCentralWidget(textEditor)
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()