问题描述
如何在 pyqt5 中实现关键监听器?即使应用在后台,我也想检测按键.
how can i implement a key listener in pyqt5? i want to detect keypresses even when the app is in background.
from pyqt5 import qtgui from pyqt5.qtwidgets import * from pyqt5.qtcore import qt import sys class window(qwidget): ... def keypressevent(self, e): # doesnt work when app is in background if e.key() == qt.key_f3: print(1) elif e.key() == qt.key_f4: print(0) ... app = qapplication(sys.argv) app.setstyle('fusion') window = window() sys.exit(app.exec())
推荐答案
qt 只有在其顶层窗口有键盘焦点时才能访问键盘事件.如果窗口被最小化或另一个窗口获得焦点,您将不会收到键盘事件.
qt can access keyboard events only if any of its top level window has keyboard focus. if the window is minimized or another window takes focus, you will not receive keyboard events.
唯一的百家乐凯发k8的解决方案是使用外部库,但它们有局限性.
the only solution is to use an external library, but they have limitations.
keyboard 模块似乎不支持 macos,而 pyinput 可以,但需要该操作系统的 root 访问权限.我不知道有任何其他方法可以不受限制地支持所有三个平台.
the keyboard module does not seem to support macos, while pyinput does, but requires root access for that os. i don't know of any other ways that support all three platforms without limitations.
在任何情况下,您都不应该依赖于对当前按键的定时检查,因为您最终肯定会错过一些事件.
虽然通常会使用一个单独的线程来实现事件侦听器(通常是阻塞的),但幸运的是在这两种情况下都有非阻塞系统来调用回调函数(因此您实际上不需要单独的线程).
in any case, you should not rely on timed checking of the currently pressed keys, because you'll certainly end up missing some events.
while normally one would use a separate thread that implements the event listener (which are normally blocking), luckily in both cases there are non blocking systems to call callback functions (so you don't actually need a separate thread).
以下是使用 keyboard 模块的基本示例:
the following is a basic example using the keyboard module:
from pyqt5 import qtcore, qtwidgets import keyboard class keygrabber(qtwidgets.qwidget): def __init__(self): super().__init__() layout = qtwidgets.qvboxlayout(self) self.button = qtwidgets.qpushbutton('start') layout.addwidget(self.button) self.button.setcheckable(true) self.button.toggled.connect(self.setgrabbing) def keyboardeventreceived(self, event): if event.event_type == 'down': if event.name == 'f3': print('f3 pressed') elif event.name == 'f4': print('f4 pressed') def setgrabbing(self, enable): if enable: self.button.settext('stop') # on_press returns a hook that can be used to "disconnect" the callback # function later, if required self.hook = keyboard.on_press(self.keyboardeventreceived) self.showminimized() else: self.button.settext('start') keyboard.unhook(self.hook)