使用keyPressEvent捕获输入或返回 [英] Use keyPressEvent to catch enter or return
问题描述
我有一个简单的表单,其中包含一些连击,标签,按钮和QTextEdit.
I have a simple form with some combos, labels, buttons and a QTextEdit.
我尝试使用keyPressEvent捕获回车键或返回键,但是由于某些原因,我无法. 但是,我也使用了ESC键.
I try to catch the enter or return key with keyPressEvent, but for some reason I'm not able to. The ESC key however, that I also use, is recognized.
下面是一段代码:
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:
等...
我想念什么吗?
推荐答案
从代码中还不能完全清楚,但是当您需要为文本执行此操作时,看起来您可能已经重新实现了keyPressEvent
表单.自行编辑.
It's not completely clear from your code, but it looks like you may have reimplemented keyPressEvent
for the form, when you needed to do it for the text-edit itself.
一种解决方法是使用事件过滤器,有时更加灵活,因为它避免了对您感兴趣的窗口小部件进行子类化.下面的演示脚本显示了如何使用它的基础知识.需要注意的重要一点是,事件过滤器应返回True
以停止任何进一步的处理,返回False
以将事件传递以进行进一步的处理,否则应直接进入基类事件过滤器.
One way to fix that is to use an event filter, which can sometimes be more flexible as it avoids having to sub-class the widget(s) you're interested in. The demo script below shows the basics of how to use it. The important thing to note is that the the event-filter should return True
to stop any further handling, return False
to pass the event on for further handling, or otherwise just drop through to the base-class event-filter.
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_())
这篇关于使用keyPressEvent捕获输入或返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!