Open In App

PyQt5 – How to change color of the label ?

Improve
Improve
Like Article
Like
Save
Share
Report

While creating a Label in PyQt5, we can see that there is no background color. In this article we will see how to add background color to the Label.
pyqt5-change-color-label

In order to add border to the Label we will use label.setStyleSheet() method, this will add the background color to the label, it is same like designing the CSS style sheet.

Syntax : label.setStyleSheet(“background-color: cyan”)

Argument : It takes string as argument.

Action performed: It changes the background color of the label.

Code :




# importing the required libraries
  
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 
import sys
  
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
        # set the title
        self.setWindowTitle("Label")
  
        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)
  
        # creating a label widget
        # by default label will display at top left corner
        self.label_1 = QLabel('Light green', self)
  
        # moving position
        self.label_1.move(100, 100)
  
        # setting up background color
        self.label_1.setStyleSheet("background-color: lightgreen")
  
        # creating a label widget
        # by default label will display at top left corner
        self.label_2 = QLabel('Yellow', self)
          
        # moving position
        self.label_2.move(100, 150)
  
        # setting up background color and border
        self.label_2.setStyleSheet("background-color: yellow; 
                                    border: 1px solid black;")
  
        # show all the widgets
        self.show()
  
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())


Output :
change-label-color-pyqt



Last Updated : 26 Mar, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads