如何控制Qt中的KeyEvent

时间:2016-02-14 05:29:11

标签: python qt pyqt pyside

enter image description here

将使用CustomWidget声明的窗口作为超类:class App(CustomWidget)按下Alt + A正确打印'keyPressEvent:Alt + a'消息。

但是当使用setCentralWidget()将CustomWidget分配给窗口或使用layer.addWidget(窗口小部件)设置时,KeyEvent功能会中断。代码中缺少什么?

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

2 个答案:

答案 0 :(得分:1)

小部件必须具有焦点才能接收事件。确保调用setFocusPolicy()以使CustomWidget在创建窗口后接受并保持焦点。

QWidget, keyPressEvent

QWidget, setFocusPolicy

答案 1 :(得分:0)

工作解决方案:

重要提示:在GroupBox的keyPressEvent()方法结束时,我们必须将Event传递给super。或者,事件不会传播到父窗口小部件:super(QtGui.QGroupBox, self).keyPressEvent(event)

enter image description here

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