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

2024-05-01 21:51:31 发布

您现在位置:Python中文网/ 问答频道 /正文

也许有人问过很多次,但我找不到解决办法。

我有一个对话:

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和keyrease。

所以我把它分成了子类:

class ContentEditor(QtGui.QPlainTextEdit):

    def __init__(self, parent=None):
        QtGui.QPlainTextEdit.__init__(self, parent)

    def keyPressEvent(self, event):
        print "do something"

但ContentEditor.keyPressEvent从未被调用!为什么?


Tags: selfnoneuiinitdef对话classparent
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)

可能需要调用QWidget的方法setFocusPolicy来接收按键事件。 来自方法keyPressEvent的QWidget的API文档:

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.

通过在Qt设计器中将QPlainTextEdit小部件提升到子类ContentEditor中,可以更好地完成您想要完成的工作。
Qt documentation
在“Promoted Widgets”对话框中:
“Promote类名”:ContentEditor
“头文件”:你的python模块名

相关问题 更多 >