我在代码中使用典型的子类化对 qtextedit 进行了子类化,但不知何故,即使我的信号工作正常,event.ignore 也无法工作。目标是捕获 Enter 键并单击按钮,但不在 qtextedit 上提交 Enter。
我的代码在这里:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction
from PyQt5.QtGui import QPalette
from PyQt5.QtCore import QThread , pyqtSignal
class TextEdit(QtWidgets.QTextEdit):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
keyPressed2 = pyqtSignal()
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
self.setGeometry(QtCore.QRect(30, 100, 331, 71))
self.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
self.raise_()
self.setFocus()
self.setPlaceholderText("Set 4 character ICAO Locator here , divided by spaces...")
self.keyPressed.connect(self.on_key)
def keyPressEvent(self,event):
super(TextEdit, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if event.key() == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
event.ignore()
self.keyPressed2.emit()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1371, 924)
MainWindow.setAcceptDrops(True)
self.T_aerodromes_input = TextEdit(self.centralWidget)
self.T_aerodromes_input.keyPressed2.connect(self.B_aerodrome_data.click)
self.B_aerodrome_data = QtWidgets.QPushButton(self.centralWidget)
self.B_aerodrome_data.setGeometry(QtCore.QRect(670, 100, 271, 41))
self.B_aerodrome_data.setObjectName("B_aerodrome_data")
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_())
如果你只想过滤回车或返回键,那么只需验证它们不是那些键,如果它们不是那些键,则调用父亲的方法,否则,不要这样做。
def keyPressEvent(self,event):
if event.key() not in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
super(TextEdit, self).keyPressEvent(event)
else:
self.keyPressed.emit(event)