Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context Menu not displaying correct language with PyQt5

When I was trying to create a Qt application using PyQt5, I noticed that QPlainTextEdit standard context menu was being displayed in English , which is not the language of my system (Portuguese), despite its locale was correctly inherited from its parent widget. Is this the expected behavior? If so, how can i add a translation without having to rewrite the functions already present in that context menu (like cut/copy/paste)?

Example

This program reproduces the behavior described above; it shows a window (thus textEditor.locale().language() have the same value as QLocale.Portuguese) but the context menu is shown in english.

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()
like image 981
Daniel Avatar asked Dec 05 '25 18:12

Daniel


1 Answers

You need to install a QTranslator to add the translations for your system locale.

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()
like image 81
user3419537 Avatar answered Dec 08 '25 07:12

user3419537



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!