In this lesson we want to learn about Python PySide6 Handling Key Press Event, In PySide6, you can handle key press events using keyPressEvent method of the widget you want to handle the event for. This is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from PySide6.QtWidgets import QApplication, QWidget from PySide6.QtGui import QKeyEvent from PySide6.QtCore import Qt class MyWidget(QWidget): def keyPressEvent(self, event: QKeyEvent): if event.key() == Qt.Key_Escape: # Handle the "Escape" key print("Escape key pressed") if __name__ == '__main__': app = QApplication() widget = MyWidget() widget.show() app.exec() |
In this example we have created new widget MyWidget and override keyPressEvent method. In this method we check if the key that was pressed is the “Escape” key (represented by Qt.Key_Escape), and if so, we print message to the console.
When you run this program MyWidget will be displayed, and you can press the “Escape” key to see the message printed in the console.
Note that you can check for other keys by using their corresponding Qt.Key_* values, or by using the key() method of the QKeyEvent object.
Now let’s create another example, this is an example of how you can use the key press event to move a square around in PySide6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
from PySide6.QtWidgets import QApplication, QWidget from PySide6.QtGui import QPainter, QKeyEvent, QBrush, QColor, QPen from PySide6.QtCore import Qt, QRectF class Square(QWidget): def __init__(self): super().__init__() self.setGeometry(50, 50, 200, 200) self.setWindowTitle("Move Square - GeeksCoders.com") self.pos_x = 100 self.pos_y = 100 def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(Qt.black, 2)) painter.setBrush(QBrush(QColor(255, 0, 0))) painter.drawRect(QRectF(self.pos_x, self.pos_y, 50, 50)) def keyPressEvent(self, event: QKeyEvent): if event.key() == Qt.Key_Left: self.pos_x -= 10 elif event.key() == Qt.Key_Right: self.pos_x += 10 elif event.key() == Qt.Key_Up: self.pos_y -= 10 elif event.key() == Qt.Key_Down: self.pos_y += 10 self.update() if __name__ == '__main__': app = QApplication() square = Square() square.show() app.exec() |
In this example, we have created Square widget that represents a square at fixed position. in the paintEvent method we draw the square using the QPainter class.
We override keyPressEvent method to handle arrow key presses. when the left arrow key is pressed, we move the square to the left by 10 pixels, and similarly for the right, up and down arrow keys. we update the position of the square and call update to redraw the widget with the new position.
When you run this program, you will see a red square on the screen. You can use the arrow keys to move the square around.
Run the complete code and this will be the result.