PyQt5 – How to change color of the label ?

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 :

filter_none

edit
close

play_arrow

link
brightness_4
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())

chevron_right


Output :
change-label-color-pyqt

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.