0

When I try to use key listener with pyqt5 to detect if some key is clicked. My app stops working...

the listener works well but when I use pyqt with the listener the app crashes

I want to detect if this button is pressed ']'

my code:

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore
from PyQt5.uic import loadUiType


import sys
from pynput import keyboard



class Main(QMainWindow):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)

        self.setGeometry(500, 500, 500, 300)    
        self.btn = QPushButton('start', self)
        self.btn.move(100, 100)
        self.btn.clicked.connect(lambda : self.start())


       



    def on_press(self, key):
   
        try:
            k = key.char 
        except:
            k = key.name  

        if k == ']':  
            print('dad')

        

    def start(self):
        
        self.listener = keyboard.Listener(on_press=self.on_press)   
        self.listener.start() 
        self.listener.join()
                






if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Main()
    ex.show()
    sys.exit(app.exec_())
  • You must remove the line `self.listener.join()`, because that will wait until the listener thread terminates, and therefore block the main gui thread. But there's no need to use `pynput` unless you want global hotkeys. For application-level keyboard handling, you can simply override [`keyPressEvent`](https://doc.qt.io/qt-5/qwidget.html#keyPressEvent) (for example, [like this](https://stackoverflow.com/a/27477021/984421)). – ekhumoro Oct 14 '21 at 16:43
  • it worked thanks –  Oct 14 '21 at 16:46

0 Answers0