Important: Please read the Qt Code of Conduct -

Can't add a stretched background image with PyQt5

  • Hi,

    I've been struggling with this for the last 3 days... I would like to simply add a stretched background image to my parent QWidget. I literally tried a dozens of times after searching everywhere but I'm still stuck with this issue. I don't use resources (from qt designer). PSB :

    from PyQt5 import QtCore, QtWidgets, QtGui
    import sys
    class Ui_Form(QtWidgets.QWidget):
    def __init__(self):
    def setupUi(self, Form):
        Form.resize(860, 619)
        Form.setStyleSheet("QWidget#Form {border-image: url(space.png) 0 0 0 0 stretch stretch;}") 

    And it does not work. But when I execute this:

            Form.setStyleSheet("border-image: url(space.png) 0 0 0 0 stretch stretch;")

    All Qwidget's children get the background which is obviously not what I want. But it proves at least that there is no problem with the resource itself.

    I've tried to make it work via Qpalette() and it works better but I don't know how to make the background image stretched =/ :

        image = QtGui.QImage("space.png")
        palette = QtGui.QPalette()
        palette.setBrush(10, QtGui.QBrush(image))     

    Any idea ?

  • Lifetime Qt Champion

    HI and welcome
    Maybe you can "cheat" and use a QLabel ?


    also as a note:
    Form.setStyleSheet("borde xxx
    have no type selector ("QWidget#..")
    so it applies to all childs of the form.
    "QMainwndow#" would target the form

  • Thanks for your reply, you gave me some inspiration.
    I took a look at "Qt Style Sheets Examples" and I could not find how to customize a QWidget so I simply convert my QWidget to a QMainWindow. I got rid of the menu bar and the status bar because I don't need them... everything works fine now with QMainWindow :)

    `class Ui_MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
    def setupUi(self, MainWindow):
        MainWindow.resize(856, 610)
        MainWindow.setStyleSheet("#MainWindow { border-image: url(space.png) 0 0 0 0 stretch stretch; }")
        self.centralwidget = QtWidgets.QWidget(MainWindow)

  • Lifetime Qt Champion

    super :)
    also using "#MainWindow" makes sure it dont apply to childs as stylesheets does.