You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取现有QShortcut列表并避免快捷键重复分配?

解决Qt快捷键重复分配的问题

现有代码可创建绑定快捷键的对象,但无法避免重复分配相同快捷键。要实现create_shortcut函数的重复检查功能,Qt本身没有提供直接获取现有快捷键列表的API,我们可以自行维护一个快捷键注册表来实现:

解决方案思路

  • 在父对象中维护一个集合,用于记录已注册的快捷键序列
  • 创建新快捷键前,先检查目标快捷键是否已在集合中
  • 若已存在则返回错误;若不存在则创建快捷键并将其加入集合
  • 当快捷键对象被销毁时,从集合中移除对应的记录,避免无效记录残留

修改后的代码示例

from PySide2.QtCore import QObject
from PySide2.QtGui import QKeySequence, QShortcut

class MyClass(QObject):
    def __init__(self, parent, shortcut_keys: str):
        super().__init__(parent)
        # 初始化父对象的快捷键注册表(不存在则创建)
        if not hasattr(parent, '_registered_shortcuts'):
            parent._registered_shortcuts = set()
        # 尝试创建快捷键并处理错误
        try:
            self.create_shortcut(shortcut_keys)
        except ValueError as e:
            print(f"创建快捷键失败: {e}")
            self.deleteLater()

    def create_shortcut(self, shortcut_keys) -> None:
        parent = self.parent()
        key_seq = QKeySequence(shortcut_keys)
        # 检查快捷键是否已被注册
        if key_seq in parent._registered_shortcuts:
            raise ValueError(f"快捷键 {shortcut_keys} 已存在")
        
        # 创建快捷键并绑定触发逻辑
        self.shortcut = QShortcut(key_seq, parent)
        self.shortcut.activated.connect(self.do_stuff)
        # 将新快捷键加入注册表
        parent._registered_shortcuts.add(key_seq)
        # 绑定销毁信号,用于清理注册表
        self.destroyed.connect(lambda: self._cleanup_shortcut(key_seq))

    def _cleanup_shortcut(self, key_seq):
        parent = self.parent()
        if hasattr(parent, '_registered_shortcuts') and key_seq in parent._registered_shortcuts:
            parent._registered_shortcuts.remove(key_seq)

    def do_stuff(self):
        # 快捷键触发后的业务逻辑
        print("快捷键已触发")

说明

  • 借助父对象的_registered_shortcuts集合跟踪已注册快捷键,确保同一父对象下不会出现重复绑定
  • 通过destroyed信号在对象销毁时自动清理注册表,避免无效记录残留
  • 将字符串转为QKeySequence后再检查,统一快捷键的判定标准(不同字符串写法但实际为同一快捷键的情况会被正确识别)
  • 错误处理方式可根据需求调整,比如改为返回布尔值而非抛出异常

内容的提问来源于stack exchange,提问作者Andrew Plowright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:35:17