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屋!
查看全文