Search code examples
python-3.xqwidgetpyqt5qimageqlayout

PyQt5 - Add image in background of MainWindow layout


New to PyQt5... Here is a very basic question.

I would like to add an image inside the layout of a widget. This widget is the Main Window / root widget of my application. I use the following code, but I get an error message.

import sys

from PyQt5.QtGui import QImage
from PyQt5.QtWidgets import *

class MainWindow(QWidget):

    def __init__(self):

       super().__init__()

       self.setGeometry(300,300,300,220)
       self.setWindowTitle("Hello !")

       oImage = QImage("backgound.png")

       oLayout = QVBoxLayout()
       oLayout.addWidget(oImage)

       self.setLayout(oLayout)

       self.show()

if __name__ == "__main__":

    app = QApplication(sys.argv)

    oMainwindow = MainWindow()

    sys.exit(app.exec_())


TypeError: QBoxLayout.addWidget(QWidget, int stretch=0, Qt.Alignment alignment=0): argument 1 has unexpected type 'QImage'

Apparently a QLayoutWidget does not accept a QImage as an input. Is there a workaround to have an image appear as a brackground in a QWidget ?


Solution

  • The QVBoxLayout class lines up widgets vertically.

    documentation QVBoxLayout

    QImage is no widget.

    on many widgets e.g. QmainWindow, QLabel you can use

    widget.setStyleSheet(„ background-image: url(backgound.png);“)
    

    on my machine this doesn't work with QWidget. In this case you can use the following rewrite of your code:

    import sys
    from PyQt5.QtCore import QSize
    from PyQt5.QtGui import QImage, QPalette, QBrush
    from PyQt5.QtWidgets import *
    
    class MainWindow(QWidget):
        def __init__(self):
           QWidget.__init__(self)
           self.setGeometry(100,100,300,200)
    
           oImage = QImage("test.png")
           sImage = oImage.scaled(QSize(300,200))                   # resize Image to widgets size
           palette = QPalette()
           palette.setBrush(QPalette.Window, QBrush(sImage))                        
           self.setPalette(palette)
    
           self.label = QLabel('Test', self)                        # test, if it's really backgroundimage
           self.label.setGeometry(50,50,200,50)
    
           self.show()
    
    if __name__ == "__main__":
    
        app = QApplication(sys.argv)
        oMainwindow = MainWindow()
        sys.exit(app.exec_())