简体   繁体   中英

keyPressEvent in PyQt

I'm designing an experiment with PyQt5. All I want is during one of the windows in the stacked widget, all keys pressed will be stored in a list. This is probably a stupid question, but I have been labouring over it for a while and have reviewed at least twenty stack-overflow questions and cannot get it to work.

I tried creating a custom widget and added it to my window.

class KeyboardWidget(QWidget):
    keyPressed = pyqtSignal(str)
    def keyPressEvent(self, keyEvent):
        self.keyPressed.emit(keyEvent.key())

...

window.aList = []
def keyCounter():
    window.aList.append(keyPressEvent)
    return window.aList

if ui.screens.currentIndex() == 4:
    breathCount = KeyboardWidget(window)
    breathCount.setFocus()
    breathCount.keyPressed.connect(keyCounter)

This is more or less what I have. I've changed a couple minor details around, but I've yet to be able to print or return any keys pressed when I run the program.

You should use keyEvent.text() to get the name of the key, the method key() returns an integer, also you were missing a parameter in your keyCounter method to receive the name of the key:

import sys

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication


class KeyboardWidget(QWidget):
    keyPressed = pyqtSignal(str)

    def keyPressEvent(self, keyEvent):
        self.keyPressed.emit(keyEvent.text())


class MyApplication(QApplication):
    def __init__(self, args):
        super().__init__(args)

        self.keyList = []

        self.keyboardWidget = KeyboardWidget()
        self.keyboardWidget.keyPressed.connect(self.keyCounter)

        self.keyboardWidget.show()

    def keyCounter(self, key):
        self.keyList.append(key)
        print(key)


if __name__ == '__main__':
    app = MyApplication(sys.argv)
    sys.exit(app.exec_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM