我在PyQt5中使用site-packages/PyQt5/translations
文件夹中的qt_xx.qm翻译QTextEdit、QPlainTextEdit和QTextBrowser的默认上下文菜单时遇到问题。例如,它适用于QLineEdit(这是相同的上下文菜单)。如何处理?
再现问题的代码:
# coding: utf-8
import sys
from PyQt5.QtCore import QLocale
from PyQt5.QtCore import QTranslator
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QTextEdit
from PyQt5.QtWidgets import QVBoxLayout
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
widget = QWidget()
lineEdit = QLineEdit()
textEdit = QTextEdit()
vbox = QVBoxLayout(widget)
vbox.addWidget(lineEdit)
vbox.addWidget(textEdit)
self.setCentralWidget(widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
locale = QLocale.system().name()
qtTranslator = QTranslator()
if qtTranslator.load('C:/Python33/Lib/site-packages/PyQt5/translations/qt_' + locale):
app.installTranslator(qtTranslator)
mainWindow = MainWindow()
mainWindow.show()
app.exec_()
我遇到了同样的问题,我试图通过修改通过调用方法QTextEdit::createStandardContext
创建的标准上下文菜单来解决这个问题,它确实起到了作用
这是代码:
void CWQTextEdit::contextMenuEvent(QContextMenuEvent *e)
{
QMenu *menu = QTextEdit::createStandardContextMenu();
if (menu == NULL)
return QTextEdit::contextMenuEvent(e);
QList<QAction*> actions = menu->actions();
foreach (QAction *action, actions)
{
QString actionText = action->text();
if (actionText.contains("Undo"))
{
actionText.replace("Undo", tr("Undo"));
action->setText(actionText);
}
else if (actionText.contains("Redo"))
{
actionText.replace("Redo", tr("Redo"));
action->setText(actionText);
}
else if (actionText.contains("Cu&t"))
{
actionText.replace("Cu&t", tr("Cut"));
action->setText(actionText);
}
else if (actionText.contains("Copy"))
{
actionText.replace("Copy", tr("Copy"));
action->setText(actionText);
}
else if (actionText.contains("Paste"))
{
actionText.replace("Paste", tr("Paste"));
action->setText(actionText);
}
else if (actionText.contains("Delete"))
{
actionText.replace("Delete", tr("Delete"));
action->setText(actionText);
}
else if (actionText.contains("Select All"))
{
actionText.replace("Select All", tr("Select All"));
action->setText(actionText);
}
}
menu->exec(e->globalPos());
}
if __name__ == "__main__":
app = QApplication(argv)
translator = QtCore.QTranslator()
translator.load("translations/qt_zh_CN.qm")
app.installTranslator(translator)