1

I am trying since a little while to simply display an image in background of a QFrame and simply can't. I can see loads of example on the net but none of them seems to work with my code, and I can't understand why :

import sys, random
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QPalette, QBrush, QPixmap

class MainWin(QtGui.QMainWindow):
    def __init__(self):
        super(MainWin, self).__init__()
        self.initUI()

    def initUI(self):
        #central widget
        self.theboard = Board(self)
        self.setCentralWidget(self.theboard)
        self.resize(360, 760)
        self.setWindowTitle('Name')
        self.show()

class Board(QtGui.QFrame):
    def __init__(self, parent):
        super(Board, self).__init__(parent)
        self.initBoard()

    def initBoard(self):
        print("ddd")
        frame = Board
        palette = QPalette(self)
        palette.setBrush(QPalette.Background,QBrush(QPixmap("ImageTest.jpg")))
        frame.setPalette(palette)

def main():
    app = QtGui.QApplication([])
    mw = MainWin()
    sys.exit(app.exec_())

if __name__ == '__main__':

    main()

will return:

TypeError: QWidget.setPalette(QPalette): first argument of unbound method must have type 'QWidget'

If I don't pass my QFrame in a variable and do as such :

palette = QPalette(self)
palette.setBrush(QPalette.Background,QBrush(QPixmap("ImageTest.jpg")))
self.setPalette(palette)

No more errors but my background is still blank. Same thing if I just try to fill a color instead of the image.

1 Answer 1

1

Unless it's a top-level widget, you need to set the autoFillBackground property to get this to work:

    def initBoard(self):
        self.setAutoFillBackground(True)
        palette = QPalette(self)
        palette.setBrush(QPalette.Background, QBrush(QPixmap("ImageTest.jpg")))
        self.setPalette(palette)

Alternatively, and more simply, use a style-sheet to set the background image:

    def initBoard(self):
        self.setStyleSheet('background-image: url("ImageTest.jpg")')
Sign up to request clarification or add additional context in comments.

1 Comment

That's wonderful thank you so much for your answer, all good now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.