PyQt5系列教程(二十六)设置背景图片
source link: https://xugaoxiang.com/2022/04/26/pyqt5-26-stylesheet/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
软硬件环境
- Windows 10 64bit
- Anaconda3 with python 3.7
- PyQt5
为了界面美观,有时候需要设置窗口的背景图片,本篇就来实现这个需求。
使用 designer
设计一个简单的界面,拖动三个 push button
到窗口中,调整下大小、位置,保存成 .ui
文件后,使用 pyuic
进行代码转换
pyuic5.bat -o ui.py project.ui
来到工程入口文件 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_())
还是熟悉的,app
实例化,然后使用 setStyleSheet
方法来设置样式,在属性 background-image
写上背景图片的地址,这里还支持网络图片地址。可以看到在标签中我们写的是 MainWindows
,也就是我们设置的是这个窗口的样式,从而达到设置整个窗口背景图的目的。
上述代码执行后,效果如下
除了用代码来设置样式,其实在 designer
也可以完成,选择控件,然后右键选择 改变样式表
资源这块使用的是 Qt
自有的 qrc
资源文件,这里以设置第一个按钮的背景图为例,点击添加资源下的image
新建一个资源文件,并将背景文件放进来
qrc
文件跟 xml
文件比较类似,用来指定资源文件的路径
<RCC>
<qresource>
<file>bg.jpg</file>
</qresource>
</RCC>
除此之外,还可以设置背景颜色、边缘、字体等,大家可以自己去玩玩
https://github.com/xugaoxiang/learningPyQt5
PyQt5系列教程
更多PyQt5
教程,请移步
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK