内容来自于《PyQT5快速开发与实战》
窗口背景主要包括:背景颜色和背景图片
如果要给控件设置背景图片或图片,可以使用setIcon()或setPixmap()来完成。
# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys
app = QApplication(sys.argv)
window = QMainWindow()
window.setObjectName("MainWindow")
window.setStyleSheet("#MainWindow{border-image:url(background.jpg)}") # 这里使用相对路径,也可以使用绝对路径
window.show()
sys.exit(app.exec_())
# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys
app = QApplication(sys.argv)
window = QMainWindow()
window.setObjectName("MainWindow")
window.setStyleSheet("#MainWindow{background-color:green}")
window.show()
sys.exit(app.exec_())
# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPalette
from PyQt5.QtCore import Qt
import sys
app = QApplication(sys.argv)
window = QMainWindow()
palette = QPalette()
palette.setColor(QPalette.Background, Qt.red)
window.setPalette(palette)
window.show()
sys.exit(app.exec_())
如果背景图片大小大于窗口,则图片会平铺窗口;否则会加载多个背景图片。可以调整图片的分辨率,或者调整窗口的大小来达到自己想要的效果。
# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPalette, QBrush, QPixmap
import sys
app = QApplication(sys.argv)
window = QMainWindow()
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("./background.jpg")))
window.setPalette(palette)
window.show()
sys.exit(app.exec_())
# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication,QWidget
from PyQt5.QtGui import QPalette, QBrush, QPixmap, QPainter
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
import sys
class Winform(QWidget):
def __init__(self, parent=None):
super(Winform, self).__init__(parent)
self.setWindowTitle("使用QPaintEvent设置窗口背景色")
def paintEvent(self, a0: QtGui.QPaintEvent) -> None:
painter = QPainter(self)
painter.setBrush(Qt.red)
painter.drawRect(self.rect())
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Winform()
window.show()
sys.exit(app.exec_())
# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication,QWidget
from PyQt5.QtGui import QPalette, QBrush, QPixmap, QPainter
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
import sys
class Winform(QWidget):
def __init__(self, parent=None):
super(Winform, self).__init__(parent)
self.setWindowTitle("使用QPaintEvent设置窗口背景图片")
def paintEvent(self, a0: QtGui.QPaintEvent) -> None:
painter = QPainter(self)
pixmap = QPixmap("./background.jpg")
painter.drawPixmap(self.rect(), pixmap)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Winform()
window.show()
sys.exit(app.exec_())