PyQt5 设置窗口背景
- 使用setStyleSheet设置窗口背景图片
- 使用setStyleSheet设置窗口背景颜色
- 使用QPalette设置窗口背景颜色
- 使用QPalette设置窗口背景图片
- 使用paintEvent设置窗口背景颜色
- 使用paintEvent设置窗口背景图片
窗口背景主要包括:背景色和背景图片。设置窗口背景主要有三种方法:
- 使用QSS设置窗口背景。
- 使用QPalette设置窗口背景。
- 实现paintEvent,使用QPainter绘制背景。
使用setStyleSheet设置窗口背景图片
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
if __name__ == "__main__":
app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("界面背景图片设置")
win.resize(350, 250)
win.setObjectName("MainWindow")
win.setStyleSheet("#MainWindow{border-image:url(./pyqt5/python.jpg)}")
win.show()
sys.exit(app.exec_())
使用setStyleSheet设置窗口背景颜色
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
if __name__ == "__main__":
app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("界面背景图片设置")
win.resize(350, 250)
win.setObjectName("MainWindow")
win.setStyleSheet("#MainWindow{background-color:yellow}")
win.show()
sys.exit(app.exec_())
使用QPalette设置窗口背景颜色
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
if __name__ == "__main__":
app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("QPalette调色板设置背景颜色")
win.resize(350, 150)
palette = QPalette()
palette.setColor(QPalette.Background, Qt.red)
win.setPalette(palette)
win.show()
sys.exit(app.exec_())
使用QPalette设置窗口背景图片
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
if __name__ == "__main__":
app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("QPalette设置背景图片")
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("./pyqt5/python.jpg")))
win.setPalette(palette)
win.resize(800, 600)
win.show()
sys.exit(app.exec_())
使用paintEvent设置窗口背景颜色
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class WinForm(QWidget):
def __init__(self, parent=None):
super(WinForm, self).__init__(parent)
self.setWindowTitle("paintEvent设置背景色")
def paintEvent(self, event):
painter = QPainter(self)
painter.setBrush(Qt.blue)
painter.drawRect(self.rect())
if __name__ == "__main__":
app = QApplication(sys.argv)
win = WinForm()
win.show()
sys.exit(app.exec_())
使用paintEvent设置窗口背景图片
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class WinForm(QWidget):
def __init__(self, parent=None):
super(WinForm, self).__init__(parent)
self.setWindowTitle("paintEvent设置背景图片")
def paintEvent(self, event):
painter = QPainter(self)
pixmap = QPixmap("./pyqt5/images/screen1.jpg")
painter.drawPixmap(self.rect(), pixmap)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = WinForm()
win.show()
sys.exit(app.exec_())