某些小部件将允许我做:
self.widget.clicked.connect(on_click)
但正在做:
self.widget.keyPressEvent.connect(on_key)
将失败,表明该对象没有属性“connect”。
我知道对小部件进行子类化并重新实现
keyPressEvent
方法将允许我响应事件。但是我如何才能从用户上下文中.connect()
到键盘事件?
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)
(注意:需要调用基类实现才能保持现有的事件处理)。
def keyPressEvent(self, event):
if type(event) == QtGui.QKeyEvent:
if event.key() == QtCore.Qt.Key_Space:
self.emit(QtCore.SIGNAL('MYSIGNAL'))
https://www.pythonguis.com/docs/qlineedit-widget/#connecting-signals-and-slots
search_box.textChanged.connect(self.type_ahead_search)
search_box.editingFinished.connect(self.search_signals)