How to set a background image in PyQt5?
To set a background image for a PyQt5 window, you first need to create a QPixmap object and pass the image file path to it. Then, by calling the setPalette method of QWidget, you can set the QPixmap object as the window’s background.
Here is a sample code demonstrating how to set a background image for a PyQt5 window.
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPalette, QPixmap
class MyWindow(QWidget):
def __init__(self):
super().__init__()
# 创建一个QPixmap对象,并加载图片文件
pixmap = QPixmap("background.jpg")
# 将QPixmap对象设置为窗口的背景
palette = self.palette()
palette.setBrush(QPalette.Background, pixmap)
self.setPalette(palette)
if __name__ == '__main__':
app = QApplication([])
window = MyWindow()
window.show()
app.exec_()
In this example, we have created a custom window class called MyWindow, where we load an image file named “background.jpg” in its constructor. We then use the setBrush method to set the QPixmap object as the window’s background, and then set that palette as the window’s palette.
After running this sample code, the window will display the specified background image. Please make sure to have the image file in the same folder as the code before running it, and replace the image file name with the actual file name.