OS X + Qt: How to capture all key-press events in the entire GUI?

≯℡__Kan透↙ 提交于 2020-01-24 09:28:34

问题


I have a basic question about Qt and Mac OS X. If I define a QMainWindow class and define a keyPressEvent function as below, is it not supposed to enter this function whenever a key is pressed anywhere in the MyWindow? I have some problems with it under Linux, where I do not get the keypress events if certain widgets were focused on (list views or edit boxes), but at least I get it if I focus on a button and then press a key. Under Mac OS X I do not get any response at all.

class MyWindow(QMainWindow):    
    def keyPressEvent(self, event):
        key = event.key()

        if key == Qt.Key_F:
            print("pressed F key")

Any ideas?

(using Python with PySide)

[edit] solution based on Pavels answer:

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

回答1:


When an event is used by a widget (e.g. an edit box), it is usually not propagated to its parent widgets, so you can't get these events from the parent window. You should install an event filter on the main QApplication object. This way you will receive (and filter if you want) all events.

See Event filters.



来源:https://stackoverflow.com/questions/19121955/os-x-qt-how-to-capture-all-key-press-events-in-the-entire-gui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!