如何更改QMainWindow中央窗口小部件的背景图像?

时间:2017-07-05 22:21:49

标签: python python-3.x pyqt background-image pyqt5

我正在尝试更改QMainWindow中央窗口小部件的背景图片。 QMainWindow的背景很容易改变,但是我的中心小部件无法获得相同的结果。我尝试的是代码

self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.mdi.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)

我也试过这个

self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.central_widget.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)

有人能解释一下这个问题吗?

1 个答案:

答案 0 :(得分:2)

要更改QWidget的背景图像,您应该覆盖paintEvent方法,在您的QStackedWidget中,我们创建一个继承自此的类:

class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("ninja.png"))
        QStackedWidget.paintEvent(self, event)

然后你改变了:

self.central_widget = QStackedWidget()

为:

self.central_widget = StackedWidget()

示例:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("image.png"))
        QStackedWidget.paintEvent(self, event)

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent=parent)
        self.setCentralWidget(StackedWidget())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

截图:

enter image description here

QStackedWidget的情况是一个特殊情况,因为没有显示,这用于显示其他小部件,对于那些小部件,您必须更改背景图像。

从您的代码中,他们附加的第一个小部件是QMdiArea,这也是一个特例,因为它有一个视口,应该更改。

class MdiArea(QMdiArea):
    def __init__(self, parent=None):
        QMdiArea.__init__(self, parent=parent)

    def paintEvent(self, event):
        QMdiArea.paintEvent(self, event)
        painter = QPainter(self.viewport())
        painter.drawPixmap(self.rect(), QPixmap("image.png"))

在您的代码更改中:

self.mdi = QMdiArea()

为:

self.mdi = MdiArea()

截图:

enter image description here

enter image description here