OS X + Qt:如何捕获整个GUI中的所有按键事件?

3

关于Qt和Mac OS X,我有一个基本问题。如果我定义了一个QMainWindow类并定义了以下keyPressEvent函数,那么无论何时在MyWindow中按下键盘,它不应该进入此函数吗? 在Linux下我遇到了一些问题,如果某些小部件(列表视图或编辑框)聚焦时,我无法获得按键事件,但如果我将焦点集中在按钮上然后按键,则至少可以获得按键事件,在Mac OS X下我根本没有任何响应。

class MyWindow(QMainWindow):    
    def keyPressEvent(self, event):
        key = event.key()
                
        if key == Qt.Key_F:
            print("pressed F key")

有什么想法(使用Python和PySide)吗?
2个回答

6
当小部件(例如编辑框)使用事件时,通常不会将其传播到其父小部件,因此您无法从父窗口获取这些事件。您应该在主QApplication对象上安装事件过滤器。这样,您将接收(并可以过滤)所有事件。
请参阅事件过滤器

0
基于Pavel的答案的解决方案:
import sys
from PySide.QtGui import *
from PySide.QtCore import * 


class basicWindow(QMainWindow):  

    def __init__(self):
        QMainWindow.__init__(self)

        self.edit = QLineEdit("try to type F", self)

        self.eF = filterObj(self)
        self.installEventFilter(self.eF)
        self.edit.installEventFilter(self.eF)
        self.show()

    def test(self, obj):
        print "received event", obj

class filterObj(QObject):
    def __init__(self, windowObj):
        QObject.__init__(self)
        self.windowObj = windowObj

    def eventFilter(self, obj, event):
        if (event.type() == QEvent.KeyPress):
            key = event.key()


            if(event.modifiers() == Qt.ControlModifier):
                if(key == Qt.Key_S):
                    print('standard response')

            else:                    
                if key == Qt.Key_F:
                    self.windowObj.test(obj)

            return True
        else:
            return False          


if __name__ == "__main__":
    app = QApplication(sys.argv)

    w = basicWindow()

    sys.exit(app.exec_())

这个答案是由 OP P.R. 在 CC BY-SA 3.0 下发布的,作为对问题 OS X + Qt:如何捕获整个 GUI 中的所有按键事件?编辑


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接