使用QSS设置窗口背景
在QSS中,我们可以使用background或者background-color的方式来设置背景色。设置窗口背景色之后,子控件默认会继承父窗口的背景色。如果想要为控件设置背景图片或图标,则可以使用setPixmap或者setlcon来完成。
代码示例
import sys
from PyQt5.QtWidgets import QMainWindow , QApplication
app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("界面背景图片设置")
win.resize(350, 250)
win.setObjectName("MainWindow")
win.setStyleSheet("#MainWindow{border-image:url(./images/python.jpg);}")
#win.setStyleSheet("#MainWindow{background-color: yellow}")
win.show()
sys.exit(app.exec_())
使用QPalette设置窗口背景
代码示例1
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout, QPushButton, QMainWindow
from PyQt5.QtGui import QPalette, QBrush, QPixmap
from PyQt5.QtCore import Qt
import sys
app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("界面背景颜色设置")
win.resize(350, 250)
palette = QPalette()
palette.setColor(QPalette.Background, Qt.red)
win.setPalette(palette)
win.show()
sys.exit(app.exec_())
代码示例2
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPalette, QBrush, QPixmap
app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("界面背景图片设置")
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("./images/python.jpg")))
win.setPalette(palette)
# 当背景图片的宽度和高度大于窗口的宽度和高度时
# win.resize(460, 255 )
# 当背景图片的宽度和高度小于窗口的宽度和高度时
win.resize(800, 600)
win.show()
sys.exit(app.exec_())
使用paintEvent设置窗口背景
代码示例1
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter
from PyQt5.QtCore import Qt
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.yellow);
# 设置背景颜色
painter.drawRect(self.rect());
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Winform()
form.show()
sys.exit(app.exec_())
代码示例2
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPixmap, QPainter
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("./images/screen1.jpg")
# 绘制窗口背景,平铺到整个窗口,随着窗口改变而改变
painter.drawPixmap(self.rect(), pixmap)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Winform()
form.show()
sys.exit(app.exec_())