PyQt5 – Different padding size at different edge of Label

In this article, we will see how we can add different padding size at different edges. Below is a image of label with normal padding and a label with different padding size at different edge.

In order to do this we will use setStyleSheet() method and describe padding length for each edge.

Syntax :

label.setStyleSheet("border :3px solid black;"
                    "padding-top : 20px;"
                    "padding-bottom :5px;")

Argument : It takes string as argument.

Action performed : It will add padding to respective edges with respective lengths.

Code :





# importing the required libraries
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import * 
import sys
class Window(QMainWindow):
    def __init__(self):
        # set the title
        # setting  the geometry of window
        self.setGeometry(60, 60, 600, 400)
        # creating a label widget
        self.label_1 = QLabel("padding", self)
        # moving position
        self.label_1.move(100, 100)
        # setting up the border and padding
        self.label_1.setStyleSheet("border :3px solid black; 
                                              padding :15px")
        # resizing label
        # creating a label widget
        self.label_2 = QLabel("padding", self)
        # setting up the border 
        # and adding padding of different length to different edges
        self.label_2.setStyleSheet("border :3px solid black;"
                                   "padding-top : 20px;"
                                   "padding-bottom :5px;")
        # moving position
        self.label_2.move(230, 200)
        # resizing the label
        # show all the widgets
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app

Output :

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

Article Tags :