Issue
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_())
Solution
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.
Answered By - PowerGlove
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.