也许这被问了很多遍,但是我找不到解决方案。
我有一个对话框:
class PostDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog() #code from designer!!
self.ui.setupUi(self)
self.ui.plainTextEdit = ContentEditor()
该对话框具有设计者提供的QPlainTextEdit。
我需要重写该QPlainTextEdit的keyPress和keyRelease。
所以我把它子类化了:
class ContentEditor(QtGui.QPlainTextEdit):
def __init__(self, parent=None):
QtGui.QPlainTextEdit.__init__(self, parent)
def keyPressEvent(self, event):
print "do something"
但是从未调用ContentEditor.keyPressEvent!为什么?
最佳答案
我建议为此使用installEventFilter:
看起来像:
class PostDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog() #code from designer!!
self.ui.setupUi(self)
self.ui.plainTextEdit.installEventFilter(self)
def eventFilter(self, event):
if event.type() == QtCore.QEvent.KeyPress:
# do some stuff ...
return True # means stop event propagation
else:
return QtGui.QDialog.eventFilter(self, event)
关于python - PyQt:如何在子类化的QWidget中接收键盘事件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6113352/