PyQt5 series tutorials (twenty-six) set the background image

Software and hardware environment

  • Windows 10 64bit
  • Anaconda3 with python 3.7
  • PyQt5

actual combat

In order to make the interface beautiful, sometimes it is necessary to set the background image of the window. This article will realize this requirement.

Use designer to design a simple interface, drag three push button to the window, adjust the size and position, save it as a .ui file, and use pyuic for code conversion

 pyuic5.bat -o ui.py project.ui

Come to the project entry file main.py

 import sys from PyQt5.QtWidgets import QMainWindow, QApplication from ui import Ui_MainWindow class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) if __name__ == '__main__': stylesheet = """ MainWindow { background-image: url("bg.jpg"); background-repeat: no-repeat; background-position: center; } """ app = QApplication(sys.argv) app.setStyleSheet(stylesheet) windows = MainWindow() windows.show() sys.exit(app.exec_())

It is still familiar to instantiate the app , then use the setStyleSheet method to set the style, and write the address of the background image in the attribute background-image . The network image address is also supported here. It can be seen that in the label we wrote MainWindows , that is, we set the style of this window, so as to achieve the purpose of setting the background image of the entire window.

After the above code is executed, the effect is as follows

In addition to using code to set the style, in fact, it can also be done in the designer , select the control, then right-click and select Change style sheet

The resource block uses Qt ‘s own qrc resource file. Here is an example of setting the background image of the first button. Click image under Add resources

Create a new resource file and put the background file in it

qrc file is similar to the xml file and is used to specify the path of the resource file

 <RCC> <qresource> <file>bg.jpg</file> </qresource> </RCC>

In addition, you can also set the background color, edge, font, etc., you can play by yourself

Source code download

https://github.com/xugaoxiang/learningPyQt5

PyQt5 series of tutorials

For more PyQt5 tutorials, please move

https://xugaoxiang.com/category/python/pyqt5/

This article is reprinted from https://xugaoxiang.com/2022/04/26/pyqt5-26-stylesheet/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment