PyQt MainWindow 背景未调整大小

PyQt MainWindow background is not resizing

这是我使用的代码:

palette = QtGui.QPalette()
myPixmap = QtGui.QPixmap('test1.jpg')
myScaledPixmap = myPixmap.scaled(self.size(), QtCore.Qt.KeepAspectRatio, transformMode = QtCore.Qt.SmoothTransformation)
palette.setBrush(QtGui.QPalette.Window, myScaledPixmap)
self.setPalette(palette)

确实显示了背景图像,但它不会在主窗口调整大小时调整大小。我已经尝试了 size() 和 frameSize()。我该如何解决这个问题以便调整背景图片的大小?

这一行:

palette.setBrush(QtGui.QPalette.Window, myScaledPixmap)

应该是这样的:

palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(myScaledPixmap))

如果你查看文档 http://pyqt.sourceforge.net/Docs/PyQt4/qpalette.html#setBrush-2 第二个参数必须是 QBrush,而不是 QPixmap

以下代码是一个工作示例:

from PyQt4 import QtGui, QtCore

class MyWin(QtGui.QWidget):

    def resizeEvent(self, event):
        palette = QtGui.QPalette()
        myPixmap = QtGui.QPixmap('test1.jpg')
        myScaledPixmap = myPixmap.scaled(self.size(), QtCore.Qt.KeepAspectRatio, transformMode = QtCore.Qt.SmoothTransformation)
        palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(myScaledPixmap))
        self.setPalette(palette)


app = QtGui.QApplication([])

win = MyWin()
win.show()

app.exec_()