我正在尝试在QPlainTextEdit小部件上安装keyPressEvent,这样在键入时,我会正常键入内容,当我按Enter键时,它将在QPlainTextEdit中添加文本。我需要Qt Designer创建的文件QtDes.py和另一个文件QtTextEvent.py。这些是我的文件:
QtDes.py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'QtDes.ui'
#
# Created by: PyQt5 UI code generator 5.13.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtGui, QtWidgets, QtCore
class Ui_MainWindow(object):
def __init__(self, *args, **kwargs):
super(Ui_MainWindow, self).__init__(*args, **kwargs)
self.exactAns = ""
self.approxAns = 0
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 569)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget)
font = QtGui.QFont()
font.setFamily("Courier New")
self.plainTextEdit.setFont(font)
self.plainTextEdit.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.plainTextEdit.setTabChangesFocus(False)
self.plainTextEdit.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap)
self.plainTextEdit.setOverwriteMode(False)
self.plainTextEdit.setTabStopWidth(40)
self.plainTextEdit.setTabStopDistance(40.0)
self.plainTextEdit.setObjectName("plainTextEdit")
self.plainTextEdit.appendPlainText("First Line: ")
self.plainTextEdit.keyPressEvent = self.keyPressEvent
self.gridLayout.addWidget(self.plainTextEdit, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
和QtTextEvent.py:
from PyQt5 import QtCore, QtGui, QtWidgets
from QtDes import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
print("Enter pressed")
self.plainTextEdit.appendPlainText("New Line: ")
else:
super(MainWindow, self).keyPressEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
按Enter键即可完成操作,但按其他按钮不起作用。我从this question和this question那里得到了答案。我的实现出现问题了,我该如何解决?
答案 0 :(得分:2)
keyPressEvent方法实现了当您按下某个键,但是您要为其分配另一个未实现此逻辑的keyPressEvent(来自QMainWindow)时,即不添加文本的任务,即向QPlaintTextEdit中添加文本。因此,将一种方法分配给另一种方法是不正确的,因为您删除了小部件默认情况下的行为。
在您的情况下,只需要听键盘,并且如果您按Enter或Return键然后添加文本,然后听一个事件,则只需要一个事件过滤器即可。
为此,您必须删除QtDes.py文件中的self.plainTextEdit.keyPressEvent = self.keyPressEvent
。还可以在QtTextEvent.py文件中实现事件过滤器:
from PyQt5 import QtCore, QtGui, QtWidgets
from QtDes import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setupUi(self)
self.plainTextEdit.installEventFilter(self)
def eventFilter(self, obj, event):
if obj is self.plainTextEdit and event.type() == QtCore.QEvent.KeyPress:
if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
print("Enter pressed")
self.plainTextEdit.appendPlainText("New Line: ")
return True
return super(MainWindow, self).eventFilter(obj, event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
另一种可能的解决方案是从QPlainTextEdit继承并覆盖keyPressEvent方法。
plaintextedit.py
class PlainTextEdit(QtWidgets.QPlainTextEdit):
def keyPressEvent(self, event):
if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
print("Enter pressed")
self.appendPlainText("New Line: ")
return
super(PlainTextEdit, self).keyPressEvent(event)
然后您更改为:
QtDes.py
from plaintextedit import PlainTextEdit
# ...
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
# ...
self.plainTextEdit = PlainTextEdit(self.centralwidget)
# ...
(您也可以promote it,如我在此答案中指出的那样)
答案 1 :(得分:0)
您不能“安装keyPressEvent”,即使可以,也无法使用您的方法。
这样做:
self.plainTextEdit.keyPressEvent = self.keyPressEvent
您实际上正在执行以下操作:
mainWindowInstance.plainTextEdit.keyPress = mainWindowInstance.keyPressEvent
结果是该事件将不会被plainTextEdit接收,但是会被主窗口接收,并且由于事件总是在不处理的情况下被发送回父对象,因此不会发生任何其他事情。
一种理论上的解决方案是改为针对QPlainTextEdit小部件调用基类实现:
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
print("Enter pressed")
self.plainTextEdit.appendPlainText("New Line: ")
else:
QtWidgets.QPlainTextEdit.keyPressEvent(self.plainTextEdit, event)
请注意,我没有致电self.plainTextEdit.keyPressEvent(event)
,因为这会导致递归。
这个想法无论如何都不是好主意,因为这样也将覆盖QMainWindow keyPressEvent(如果需要它可能会出现问题,但这不是重点)。
有两种可能的(以及更多“优雅”的)解决方案:
此方法允许您在设计器中创建UI并为自定义窗口小部件设置基本参数,您可以使用自己的代码进行扩展;有关该过程的说明,请参见this answer。
使用此方法,您可以执行以下操作:
class MyTextEdit(QtWidget.QPlainTextEdit):
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
print("Enter pressed")
self.appendPlainText("New Line: ")
else:
super().keyPressEvent(event)
额外的优势在于,这样,代码也更加简洁,易于实现。
事件过滤器能够“拦截”小部件接收的任何 事件,并可能对其做出反应。在您的情况下,可能是这样的:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.plainTextEdit.installEventFilter(self)
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.KeyPress and
event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return)):
# ensure that the widget receives the key event
super().eventFilter(source, event)
print("Enter pressed")
self.plainTextEdit.appendPlainText("New Line: ")
# the event is accepted and not sent to its ancestors
return True
return super().eventFilter(source, event)