窗口背景主要包括:背景色和背景图片。设置窗口背景主要有三种方法:
- 使用QSS设置窗口背景;
- 使用QPalette设置窗口背景;
- 实现paintEvent,使用QPainter绘制背景。
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Demo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(500,500)
self.setWindowTitle('设置窗口背景图片')
self.setObjectName('win')#设置窗口名,相当于CSS中的ID
self.setStyleSheet('#win{border-image:url(python.jpg);}')#设置图片的相对路径
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Demo()
form.show()
sys.exit(app.exec_())
运行效果如下:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Demo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(500,500)
self.setWindowTitle('设置窗口背景色')
self.setObjectName('win')#设置窗口名,相当于CSS中的ID
self.setStyleSheet('#win{background-color:blue;}')#设置窗口背景颜色
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Demo()
form.show()
sys.exit(app.exec_())
运行效果如下:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Demo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(500,500)
self.setWindowTitle('设置窗口背景色')
palette = QPalette()
palette.setColor(QPalette.Background,Qt.red)#设置窗口背景颜色
self.setPalette(palette)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Demo()
form.show()
sys.exit(app.exec_())
运行效果如下:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Demo(QMainWindow):
def __init__(self):
super().__init__()
#self.resize(500,500) # 背景图片的宽度和高度大于窗口的高度和宽度
self.resize(600, 600) # 背景图片的宽度和高度小于窗口的高度和宽度
self.setWindowTitle('设置窗口背景图片')
palette = QPalette()
palette.setBrush(QPalette.Background,QBrush(QPixmap('python.jpg')))
self.setPalette(palette)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Demo()
form.show()
sys.exit(app.exec_())
图1为背景图片宽度和高度小于窗口高度和宽度,图2为背景图片宽度和高度大于窗口高度和宽度:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Demo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(500,500)
self.setWindowTitle('设置窗口背景色')
def paintEvent(self, event):
painter = QPainter(self)
painter.setBrush(Qt.black) #设置背景色为黑色
painter.drawRect(self.rect())
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Demo()
form.show()
sys.exit(app.exec_())
运行效果如下:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Demo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(500,500)
self.setWindowTitle('设置窗口背景图片')
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(self.rect(),QPixmap('python.jpg')) #设置窗口背景图片,平铺到整个窗口,随着窗口的变化而变化
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Demo()
form.show()
sys.exit(app.exec_())
运行效果如下: