PyQt5怎么添加背景图
时间: 2024-04-07 21:07:36 浏览: 6
PyQt5可以通过QPixmap和QPalette来添加背景图。以下是一个简单的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPixmap, QPalette
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 设置窗口大小和位置
self.setGeometry(300, 300, 300, 220)
# 设置窗口标题
self.setWindowTitle('背景图')
# 创建QPixmap对象并加载图片
pixmap = QPixmap('bg.jpg')
# 创建QPalette对象
palette = QPalette()
# 将背景图设置为QPixmap对象
palette.setBrush(QPalette.Background, QPixmap(pixmap))
# 将QPalette对象设置为窗口的调色板
self.setPalette(palette)
# 显示窗口
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
在上面的代码中,我们首先创建一个QPixmap对象并加载背景图片。然后,我们创建一个QPalette对象,并将背景图设置为QPixmap对象,最后将QPalette对象设置为窗口的调色板。这样就可以将背景图设置为窗口的背景了。