【问题标题】:QShortcut & QKeySequence with Shift+Return in a QPlainTextEdit element在 QPlainTextEdit 元素中使用 Shift+Return 的 QShortcut 和 QKeySequence
【发布时间】:2020-11-18 17:36:38
【问题描述】:

我有一个元素 editorBox,它是 PyQt5 元素类型 QPlainTextEdit。我的目标是在按下热键Shift + Return 时调用一个函数,而我对这个函数的目标是它还将文本插入到 editorBox 元素中(这不是我强调的部分,它相当容易与.insertPlainText() 方法有关)。

我已经完成了搜索,我能找到的最接近的结果是将QShortcutQKeySequence 配对使用,如下所示:

# Initialize the QShortcut class
self.keybindShiftEnter = QShortcut(QKeySequence("Shift+Return"), self)
# Connect the shortcut event to a lambda which executes my function
self.keybindShiftEnter.activated.connect(lambda: self.editorBox.insertPlainText("my text to insert"))

为了澄清,我尝试在QKeySequence 构造函数中使用其他字符,例如Ctrl+b,并且我已经成功了。奇怪的是,只有 Shift+Return 组合对我不起作用。

我已经分析了一个与我的错误有关的问题。我看过的一些帖子:

【问题讨论】:

  • 实现keyPressEvent 解决方案,只要按键不匹配shift-enter,您只需调用基类实现即可。

标签: python pyqt5 keyboard-shortcuts qkeysequence qshortcut


【解决方案1】:

解决了我自己的问题:

# ... editorBox Initialization code ...
self.editorBox.installEventFilter(self)

# Within App class
def eventFilter(self, obj, event):
    if obj is self.editorBox and event.type() == QEvent.KeyPress:
        if isKeyPressed("return") and isKeyPressed("shift"):
            self.editorBox.insertPlainText("my text to insert")
            return True
    return super(App, self).eventFilter(obj, event)

我在这里做的是设置一个过滤功能——基本上,每次按下一个键(任何键,包括空格/退格/等)它都会调用eventFilter 函数。第一个if 语句确保过滤器只有在击键时才会通过(不完全确定这部分是否必要,我认为点击不会触发该功能)。之后,我利用isKeyPressed 函数(keyboard 模块的is_pressed 函数的重命名版本)来检测当前键是否被按住。使用and 运算符,我可以使用它来制作键绑定组合。

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2017-06-06
    相关资源
    最近更新 更多