简体   繁体   中英

How to have a key press event work without defining class objects?

I am having some trouble getting a key press event to work for pyqt5. Yet, I don't really want to define a class object for the window to start up either.

import os, sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from PyQt5.QtGui import *

app = QApplication(sys.argv)

Camera = QWidget()
Camera.setGeometry(100, 100, 600, 400)
Camera.setWindowTitle('James Strand Pi Camera Gui 1.0.0')

def keyPressEvent(event):
    if event.key() == Qt.Key_Enter:
        print('test')
        
button = QPushButton('test', Camera)

keyPressEvent(event)

Camera.show()
sys.exit(app.exec())

Here is the error if needed.

NameError: name 'event' is not defined

A simple but not recommended solution is to assign the function to the object to replace the default function:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget

app = QApplication(sys.argv)

camera = QWidget()
camera.setGeometry(100, 100, 600, 400)
camera.setWindowTitle("James Strand Pi Camera Gui 1.0.0")


def keyPressEvent(event):
    if event.key() in (Qt.Key_Enter, Qt.Key_Return):
        print("test")


button = QPushButton("test", camera)

camera.keyPressEvent = keyPressEvent

camera.show()
sys.exit(app.exec())

If the keys are specific then you can use QShortcut:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QApplication, QPushButton, QShortcut, QWidget

app = QApplication(sys.argv)

camera = QWidget()
camera.setGeometry(100, 100, 600, 400)
camera.setWindowTitle("James Strand Pi Camera Gui 1.0.0")


def foo():
    print("test")


button = QPushButton("test", camera)

for key in (Qt.Key_Enter, Qt.Key_Return):
    shorcut = QShortcut(QKeySequence(key), camera)
    shorcut.activated.connect(foo)

camera.show()
sys.exit(app.exec())

Another option is to create a class that monitors the keystrokes of the button through an event filter and uses signal to send the information:

import sys
from PyQt5.QtCore import pyqtSignal, QEvent, QObject, Qt
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget


class KeyHelper(QObject):
    keyPressed = pyqtSignal(Qt.Key)

    def __init__(self, widget):
        super().__init__(widget)
        self._widget = widget
        self.widget.installEventFilter(self)

    @property
    def widget(self):
        return self._widget

    def eventFilter(self, source, event):
        if source is self.widget and event.type() == QEvent.KeyPress:
            self.keyPressed.emit(event.key())
        return super().eventFilter(source, event)


app = QApplication(sys.argv)

camera = QWidget()
camera.setGeometry(100, 100, 600, 400)
camera.setWindowTitle("James Strand Pi Camera Gui 1.0.0")


def foo(key):
    if key in (Qt.Key_Enter, Qt.Key_Return):
        print("test")


button = QPushButton("test", camera)

helper = KeyHelper(camera)
helper.keyPressed.connect(foo)

camera.show()
sys.exit(app.exec())

Note: Qt::Key_Enter is only emitted when using a keypad, if a keyboard is used then a Qt::Key_Return must be used.

Some basic setup:

import os, sys
from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from PyQt5.QtGui import *




class mainProgram(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        super(mainProgram, self).__init__(parent)

        self.Camera = QWidget()
        self.Camera.setGeometry(100, 100, 600, 400)
        self.Camera.setWindowTitle('James Strand Pi Camera Gui 1.0.0')


        
        self.button  = QtWidgets.QPushButton(self)
        self.button.setGeometry(QtCore.QRect(380, 450, 151, 51))
        self.button.setObjectName("button ")
        
        self.button.clicked.connect(self.my_function)

    def my_function(self):
        #do whatever you want here

        self.Camera.show()
    
    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    nextGui = mainProgram()
    nextGui.showMaximized()
    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