Open In App

PyQt5 – Move the Label Position within the window using Arrow Keys

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article we will see how we can move the label within the window using arrow keys i.e when ever the arrow key(direction key) get pressed it moves towards that direction. For example when user press the Up arrow key the label will move upward similarly for other arrow keys label will change its position as well. Concept : We can change the position of the label by incrementing/decrementing the co-ordinate values of the label but do not increment or decrement if it reaches any end of the side below is the data given to do when each arrow key is pressed.

When Up arrow key is pressed : X Co-ordinate remain same, decrement the Y Co-ordinate 
When Down arrow key is pressed : X Co-ordinate remain same, increment the Y Co-ordinate 
When Left arrow key is pressed : Decrement X Co-ordinate, Y Co-ordinate remain same
When Right arrow key is pressed : Increment X Co-ordinate, Y Co-ordinate remain same

Below is the edges restriction data so that label should remain in the window

For top edge the y- co-ordinate should be always greater than 0 For bottom edge the y- co-ordinate should be always less than height of window – height of label For left edge the x- co-ordinate should be always greater than 0 For right edge the x- co-ordinate should be always less than width of window – width of label

Implementation Steps : 1. Create a Main window 2. Create a label inside the main window 3. Add style sheet geometry to the label 4. Create a speed variable 5. Override the key press event 6. Inside the key press event get the current x and y co-ordinates of the label 7. And check which key key is pressed and check if side end is not reached then update the x and y co-ordinates with the help of move method by incrementing/decrementing speed value from them

Below is the implementation 

Python3




# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
 
 
class Window(QMainWindow):
 
    def __init__(self):
        super().__init__()
 
        # setting title
        self.setWindowTitle("Python ")
 
        # width of window
        self.w_width = 500
 
        # height of window
        self.w_height = 500
 
        # setting geometry
        self.setGeometry(100, 100, self.w_width, self.w_height)
 
        # calling method
        self.UiComponents()
 
        # showing all the widgets
        self.show()
 
        # speed variable
        self.speed = 15
 
    # method for components
    def UiComponents(self):
 
        # creating a label
        self.label = QLabel(self)
 
        # label width
        self.l_width = 40
 
        # label height
        self.l_height = 40
 
        # setting geometry to the label
        self.label.setGeometry(200, 200, self.l_width, self.l_height)
 
        # setting stylesheet to the label
        self.label.setStyleSheet("QLabel"
                                 "{"
                                 "border : 4px solid darkgreen;"
                                 "background : lightgreen;"
                                 "}")
 
 
 
    # override the key press event
    def keyPressEvent(self, event):
 
        # get the current co-ordinates of the label
        # X Co-ordinate
        x = self.label.x()
 
        # Y Co-ordinate
        y = self.label.y()
 
        # if up arrow key is pressed
        if event.key() == Qt.Key_Up:
 
            # if top position is attained
            if y > 0:
                self.label.move(x, y - self.speed)
 
        # if down arrow key is pressed
        elif event.key() == Qt.Key_Down:
 
            # if bottom position is attained
            # for bottom point, bottom co-ordinate will be
            # height of window - height of label
            if y < self.w_height - self.l_height:
                self.label.move(x, y + self.speed)
 
        # if left arrow key is pressed
        elif event.key() == Qt.Key_Left:
 
            # if left end position is attained
            if x > 0:
                self.label.move(x - self.speed, y)
 
        # if down arrow key is pressed
        elif event.key() == Qt.Key_Right:
 
            # if right end position is attained
            # for right end point, right co-ordinate will be
            # width of window - width of label
            if x < self.w_width - self.l_width:
                self.label.move(x + self.speed, y)
 
 
 
 
 
# create pyqt5 app
App = QApplication(sys.argv)
 
# create the instance of our Window
window = Window()
 
# start the app
sys.exit(App.exec())


Output :



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads