KeyPressEvent without Focus

后端 未结 1 1052
余生分开走
余生分开走 2021-01-26 21:27

I am programming a simple GUI, that will open a opencv window at a specific point. This window has some very basic keyEvents to control it. I want to advance this with a few fun

相关标签:
1条回答
  • 2021-01-26 22:26

    The keyPressEvent method is only invoked if the widget has the focus so if the focus has another application then it will not be notified, so if you want to detect keyboard events then you must handle the OS libraries, but in python they already exist libraries that report those changes as pyinput(python -m pip install pyinput):

    import sys
    
    from PyQt5 import QtCore, QtWidgets
    
    from pynput.keyboard import Key, Listener, KeyCode
    
    
    class KeyMonitor(QtCore.QObject):
        keyPressed = QtCore.pyqtSignal(KeyCode)
    
        def __init__(self, parent=None):
            super().__init__(parent)
            self.listener = Listener(on_release=self.on_release)
    
        def on_release(self, key):
            self.keyPressed.emit(key)
    
        def stop_monitoring(self):
            self.listener.stop()
    
        def start_monitoring(self):
            self.listener.start()
    
    
    class MainWindow(QtWidgets.QWidget):
        pass
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
    
        monitor = KeyMonitor()
        monitor.keyPressed.connect(print)
        monitor.start_monitoring()
    
        window = MainWindow()
        window.show()
    
        sys.exit(app.exec_())
    
    0 讨论(0)
提交回复
热议问题