Python中使用PyQt5创建的窗口添加全局快捷键
使用第三方库SystemHotKey来实现全局快捷键
- 库的安装
pip3 install system_hotkey
- 官方案例
from system_hotkey import SystemHotkey
hk = SystemHotkey()
hk.register(('control', 'shift', 'h'), callback=lambda x: print("Easy!"))
简单思路
- 准备一个PyQt信号,和一个热键信号
sig_hk = pyqtSignal(str)
self.hk_test = SystemHotkey()
- 绑定热键信号到PyQt信号
self.hk_test.register(('control','6'),callback=lambda x:self.sendkeyevent("control+6"))
def sendkeyevent(self,i_str):
self.sigkeyhot.emit(i_str)
- 绑定PyQt信号和PyQt槽
self.sigkeyhot.connect(self.KeypressEvent)
完整案例
from system_hotkey import SystemHotkey
from PyQt5.QtWidgets import QApplication,QWidget,QDialog
from PyQt5.QtCore import QObject,pyqtSignal
class c_demo(QWidget,QObject):
sigkeyhot = pyqtSignal(str)
def __init__(self,From):
super().__init__(From)
From.resize(100,150)
self.sigkeyhot.connect(self.KeypressEvent)
self.hk_start,self.hk_stop = SystemHotkey(),SystemHotkey()
self.hk_start.register(('control','6'),callback=lambda x:self.sendkeyevent("control+6"))
self.hk_stop.register(('control', '8'), callback=lambda x: self.sendkeyevent("control+8"))
def KeypressEvent(self,i_str):
print("按下的按键是%s" % (i_str,))
def sendkeyevent(self,i_str):
self.sigkeyhot.emit(i_str)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
Dialog_main = QDialog()
ui = c_demo(Dialog_main)
Dialog_main.show()
sys.exit(app.exec_())
运行结果
-
在Python中右键,点击Run
-
在键盘上按住control+6,结果显示