如何叠加QKeyEvents

时间:2016-02-13 08:42:43

标签: python qt pyqt pyside

enter image description here

此对话框继承自QMainWindow。当按下Alt + A组合键时,其keyPressEvent()方法会打印出一条消息。

蓝色方块为QLabel。出于意图,它也应该打印消息,但仅在按下Alt + Z键时才打印。但QMainWindow阻止了QLabel的KeyEvents。即使将鼠标光标放在蓝色QLabel上,按下Alt + Z也不会触发响应。 有没有办法叠加或总结两个小部件的事件?那么Alt + Z和Alt + A都有效吗?

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_())

1 个答案:

答案 0 :(得分:1)

您需要将活动从QMainWindow传播到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)