Reputation: 19329
With the window declared with CustomWidget as super class: class App(CustomWidget)
hitting Alt+A properly prints 'keyPressEvent: Alt + a' message.
But the KeyEvent functionality is broken when the CustomWidget is assigned to window with setCentralWidget() or is set with layer.addWidget(widget). What is missing in a code?
from PyQt4 import QtCore, QtGui
class CustomWidget(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent=parent)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.AltModifier:
if event.key() == QtCore.Qt.Key_A:
print 'keyPressEvent: Alt + a'
# super(CustomWidget, self).keyPressEvent(event)
class App(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent=parent)
centralWidget = CustomWidget(self)
self.setCentralWidget(centralWidget)
mainLayout=QtGui.QVBoxLayout()
centralWidget.setLayout(mainLayout)
widget = CustomWidget(self)
mainLayout.addWidget(widget)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = App()
w.show()
sys.exit(app.exec_())
Upvotes: 0
Views: 373
Reputation: 19329
Important: At the end of GroupBox' keyPressEvent() method we have to pass the Event up to the super. Or the Event will not get propagated to the parent widget: super(QtGui.QGroupBox, self).keyPressEvent(event)
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent):
QtGui.QMainWindow.__init__(self, parent=parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.ControlModifier:
if event.key() == QtCore.Qt.Key_T:
print 'MainWindow: Control + t'
if event.key() == QtCore.Qt.Key_M:
print 'MainWindow: Control + m'
class GroupBox(QtGui.QGroupBox):
def __init__(self, parent=None):
QtGui.QGroupBox.__init__(self, parent=parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.ControlModifier:
if event.key() == QtCore.Qt.Key_T:
print 'GroupBox: Control + t'
if event.key() == QtCore.Qt.Key_S:
print 'GroupBox: Control + s'
super(QtGui.QGroupBox, self).keyPressEvent(event)
class App(MainWindow):
def __init__(self, parent=None):
MainWindow.__init__(self, parent=parent)
centralWidget = QtGui.QWidget(self)
self.setCentralWidget(centralWidget)
mainLayout=QtGui.QVBoxLayout()
centralWidget.setLayout(mainLayout)
groupBox = GroupBox(self)
mainLayout.addWidget(groupBox)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = App()
w.show()
sys.exit(app.exec_())
Upvotes: 0
Reputation: 177
The widget must have focus to receive the event. Make sure you call setFocusPolicy() to have the CustomWidget accept and maintain focus after creating the window.
Upvotes: 1