PyQt 连接到 KeyPressEvent [英] PyQt Connect to KeyPressEvent
本文介绍了PyQt 连接到 KeyPressEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
某些小部件将允许我执行以下操作:
Certain widgets will allow me to do:
self.widget.clicked.connect(on_click)
但是在做:
self.widget.keyPressEvent.connect(on_key)
将失败说对象没有属性connect".
will fail saying that the object has no attribute 'connect'.
我知道对小部件进行子类化并重新实现 keyPressEvent
方法将使我能够响应事件.但是我怎样才能.connect()
到键盘事件之后,或者说,从用户上下文?
I know that sub-classing the widget and re-implementing the keyPressEvent
method will allow me to respond to the event. But how can I .connect()
to the keyboard event thereafter, or otherwise said, from a user context?
推荐答案
创建自定义信号,并从重新实现的事件处理程序中发出它:
Create a custom signal, and emit it from your reimplemented event handler:
class MyWidget(QtGui.QWidget):
keyPressed = QtCore.pyqtSignal(int)
def keyPressEvent(self, event):
super(MyWidget, self).keyPressEvent(event)
self.keyPressed.emit(event.key())
...
def on_key(key):
# test for a specific key
if key == QtCore.Qt.Key_Return:
print('return key pressed')
else:
print('key pressed: %i' % key)
self.widget.keyPressed.connect(on_key)
(注意:为了保持现有的事件处理,需要调用基类实现).
(NB: calling the base-class implementation is required in order to keep the existing handling of events).
这篇关于PyQt 连接到 KeyPressEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文