没有焦点的KeyPressEvent [英] KeyPressEvent without Focus

查看:142
本文介绍了没有焦点的KeyPressEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的GUI,它将在特定点打开一个opencv窗口.这个窗口有一些非常基本的keyEvents来控制它.我想通过一些功能来推进这一点.由于我的QtGui是我的控制器,因此我认为使用KeyPressedEvent这样做是一种好方法.我的问题是,如果我在opencv窗口上处于活动状态,则无法触发KeyEvent.

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 functions. Since my QtGui is my Controller, I thought doing it with the KeyPressedEvent is a good way. My Problem is, that I cannot fire the KeyEvent, if I am active on the opencv window.

那么,如果我的Gui不在焦点内,该如何触发KeyEvent?

So How do I fire the KeyEvent, if my Gui is out of Focus?

我真的需要使用GrabKeyboard吗?

Do I really need to use GrabKeyboard?

以下代码重现了我的问题:

The following code reproduces my Problem:

import sys
from PyQt5.QtWidgets import (QApplication, QWidget)
from PyQt5.Qt import Qt
import cv2


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.first = True

    def openselect(self):
        im = cv2.imread(str('.\\images\\Steine\\0a5c8e512e.jpg'))
        self.r = cv2.selectROI("Image", im)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space and self.first:
            self.openselect()
            self.first = False
        print('Key Pressed!')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()

    win.show()
    sys.exit(app.exec_())

推荐答案

仅当窗口部件具有焦点时才调用keyPressEvent方法,因此如果焦点具有其他应用程序,则不会通知它,因此如果要检测键盘事件,那么您必须处理OS库,但是在python中,它们已经存在将这些更改报告为 pyinput的库. (python -m pip install pyinput):

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_())

这篇关于没有焦点的KeyPressEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆