使用keyPressEvent来捕捉回车键或换行键。

7

我有一个简单的表单,其中包含一些组合框、标签、按钮和一个QTextEdit。

我尝试使用keyPressEvent捕获回车键或换行键,但由于某种原因我无法做到。然而,我也使用了ESC键,并且可以被识别。

这是一段代码:

 def keyPressEvent(self, e):
    print e.key()
    if e.key() == QtCore.Qt.Key_Return:
        self.created.setText('return')
    if e.key() == QtCore.Qt.Key_Enter:
        self.created.setText('enter')
    if e.key() == QtCore.Qt.Key_Escape:
        self.cmbEdit = not(self.cmbEdit)
        if self.cmbEdit:

我有遗漏的地方吗?

etc...

(说明:此处“等等”为省略内容)
1个回答

8
从你的代码中并不完全清楚,但看起来你可能已经为表单重新实现了 keyPressEvent,而你需要为文本编辑器实现它。
解决的一种方法是使用 事件过滤器,这有时更加灵活,因为它避免了必须对感兴趣的小部件进行子类化。下面的示例演示了如何使用它的基础知识。要注意的重要事情是,事件过滤器应该返回 True 以停止任何进一步处理,返回 False 以传递事件进行进一步处理,或者其他情况下只需转到基类事件过滤器。
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QTextEdit(self)
        self.edit.installEventFilter(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)

    def eventFilter(self, widget, event):
        if (event.type() == QtCore.QEvent.KeyPress and
            widget is self.edit):
            key = event.key()
            if key == QtCore.Qt.Key_Escape:
                print('escape')
            else:
                if key == QtCore.Qt.Key_Return:
                    self.edit.setText('return')
                elif key == QtCore.Qt.Key_Enter:
                    self.edit.setText('enter')
                return True
        return QtGui.QWidget.eventFilter(self, widget, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 300)
    window.show()
    sys.exit(app.exec_())

就是这样!我必须将它“附加”到文本编辑器上,它会对表单事件做出反应。想法是在按下回车键时使用文本编辑器的内容进行SQL更新。 - zappfinger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接