ウィジェットにevent filterをインストールし、トラップKeyPressイベント:
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.widget = QtGui.QWidget(self)
self.widget.setFocusPolicy(QtCore.Qt.StrongFocus)
self.widget.installEventFilter(self)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.widget)
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.KeyPress and
source is self.widget):
print('key pressed: %s' % event.text())
return True
return QtGui.QWidget.eventFilter(self, source, event)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
window.resize(320, 240)
sys.exit(app.exec_())
注例では、これらのイベントの任意のさらなる処理を停止する、すべてのキープレスのTrue
を返すこと。イベントを処理しないでイベントを「聴く」だけの場合は、eventFilter
がFalse
を返すことを確認してください。
私はチェックしました!あなたはいつも私に道を示す!私は本当にあなたの世話をしてくれて本当にありがとう –