Issue
This dialog inherits from QMainWindow. Its keyPressEvent()
method prints out a message when a combination of Alt + A keys are pressed.
The blue square is QLabel
. By an intention it should print the message too but only when Alt + Z keys are pressed. But QMainWindow blocks QLabel's KeyEvents. Even if after the mouse cursor is placed over the blue QLabel hitting Alt + Z triggers no response.
Is there a way to overlay or to sum up both widget's events together? So both Alt + Z and Alt + A work?
import sys
from PyQt4 import QtCore, QtGui
class CustomMain(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
QtGui.QMainWindow.__init__(self, *args, **kwargs)
p = self.palette()
p.setColor(self.backgroundRole(), QtCore.Qt.red)
self.setPalette(p)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.AltModifier:
if event.key() == QtCore.Qt.Key_A:
print 'QMainWindow: Alt + a'
class Custom(QtGui.QLabel):
def __init__(self, *args, **kwargs):
QtGui.QLabel.__init__(self, *args, **kwargs)
img=QtGui.QImage(64, 64, QtGui.QImage.Format_RGB32)
img.fill(QtCore.Qt.blue)
pixmap=QtGui.QPixmap(img)
self.setPixmap(pixmap)
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.AltModifier:
if event.key() == QtCore.Qt.Key_Z:
print 'QLabel: Alt + z'
class App(CustomMain):
def __init__(self, *args, **kwargs):
CustomMain.__init__(self, *args, **kwargs)
mainWidget = QtGui.QWidget()
self.setCentralWidget(mainWidget)
mainLayout=QtGui.QVBoxLayout()
mainWidget.setLayout(mainLayout)
custom=Custom()
mainLayout.addWidget(custom)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = App()
w.show()
sys.exit(app.exec_())
Solution
You need to propagate the event from QMainWindow
to the QLabel
:
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.AltModifier:
if event.key() == QtCore.Qt.Key_A:
print 'QMainWindow: Alt + a'
QtGui.QMainWindow.keyPressEvent(self, event)
Answered By - Daniele Pantaleone
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.