PyQt:如何在子类QWidget中接收键盘事件?

时间:2011-05-24 16:03:10

标签: python qt events pyqt subclass

也许这已被多次询问过,但我无法找到解决方案。

我有一个对话框:

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!为什么?

4 个答案:

答案 0 :(得分:3)

我建议您使用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)

答案 1 :(得分:2)

您要完成的工作最好通过Qt Designer中的 推广 将QPlainTextEdit小部件添加到您的子类ContentEditor。
Qt documentation
在“推荐的小部件”对话框中:
“推广课程名称”:ContentEditor
“头文件”:your_python_module_name.h

答案 2 :(得分:1)

您可能需要调用QWidget的方法setFocusPolicy来接收KeyPress事件。 来自QWidget的API文档,用于方法 keyPressEvent

This event handler, for event event, can be reimplemented in a subclass 
to receive key press events for the widget. A widget must call setFocusPolicy() 
to accept focus initially and have focus in order to receive a key press event.

答案 3 :(得分:0)

您可能只需要交换以下两行:

self.ui.setupUi(self)
self.ui.plainTextEdit = ContentEditor()

如果你这样写:

self.ui.plainTextEdit = ContentEditor()
self.ui.setupUi(self)

确保在设置UI之前绑定自定义窗口小部件。否则,您只是替换对已初始化对象的引用。