PyQt5 - Add image in background of MainWindow layout

Deadly 提交于 2019-12-06 14:27:36

问题


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 ?


回答1:


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_())


来源:https://stackoverflow.com/questions/35422490/pyqt5-add-image-in-background-of-mainwindow-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!