Sunday, November 17, 2024
Google search engine
HomeLanguagesPyQt5 – How to add image in Label background ?

PyQt5 – How to add image in Label background ?

In this article, we will see how to add background image to a label, By default, when we create a label there is no background image although we can set background color to it.

Sometimes background image is necessary. In order to set a background image we will use setStyleSheet() method.

Syntax : label.setStyleSheet(“background-image : url(image.png)”;)

Argument : It takes string as argument.

Action performed Add background image to a label.

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):
        super().__init__()
  
  
        # set the title
        self.setWindowTitle("Python")
  
        # setting  the geometry of window
        self.setGeometry(60, 60, 600, 400)
  
  
        # creating a label widget
        self.label_1 = QLabel(self)
  
        # moving position
        self.label_1.move(100, 100)
  
        # setting up the border
        self.label_1.setStyleSheet("border :3px solid blue;")
  
        # setting label text
        self.label_1.setText("no background image")
  
        # creating a label widget
        self.label_2 = QLabel(self)
  
        # moving position
        self.label_2.move(160, 170)
  
        # setting up the border and adding image to background
        self.label_2.setStyleSheet("background-image : url(image.png);
                                              border : 2px solid blue")
  
  
        # setting label text
        self.label_2.setText("with background image")
        self.label_2.resize(100, 50)
  
        # 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 :
pyqt-add-backgroud-image

RELATED ARTICLES

Most Popular

Recent Comments