如何在 QWidget 上添加背景图像并在其上添加位置 QLineedit?

How add a background image on a QWidget and add positional QLineedit on top of it?

我正在尝试在 QWidget 上设置背景图像并在其上放置一些 QlineEdit。

所以知道我有这个代码

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class Model_GUI(QMainWindow):
    def __init__(self, parent= None ):
        super(Model_GUI, self).__init__()

        self.left = 0
        self.top = 0
        self.width = 800
        self.height = 800
        self.resize(self.width,self.height)

        GB = QGroupBox(" Gain ")
        GB_layout = QHBoxLayout()
        label = QLabel('A')
        edit  = QLineEdit('1')
        GB_layout.addWidget(label)
        GB_layout.addWidget(edit)
        GB.setLayout(GB_layout)

        GB2 = QGroupBox(" Gain ")
        GB_layout2 = QHBoxLayout()
        label2 = QLabel('A')
        edit2 = QLineEdit('1')
        GB_layout2.addWidget(label2)
        GB_layout2.addWidget(edit2)
        GB2.setLayout(GB_layout2)

        #Graph
        Graph = graph()

        self.CentralWidget = QWidget()
        self.globallayout = QHBoxLayout()
        self.globallayout.addWidget(GB)
        self.globallayout.addWidget(Graph)
        self.globallayout.addWidget(GB2)

        self.CentralWidget.setLayout(self.globallayout)
        self.setCentralWidget(self.CentralWidget)


class graph(QWidget):

    def __init__(self):
        super().__init__()
        self.setFixedSize(600,600)

        oImage = QImage("img.png")
        sImage = oImage.scaled(QSize(self.width(), self.height()))  # resize Image to widgets size
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))  # 10 = Windowrole
        self.setPalette(palette)

        self.label1 = QLabel('Param1', self)
        self.edit1 = QLineEdit('1', self)
        self.label2 = QLabel('Param2', self)
        self.edit2 = QLineEdit('10', self)
        self.label1.move(50, 50)
        self.edit1.move(500, 50)
        self.label2.move(50, 500)
        self.edit2.move(500, 500)


def main():
    app = QApplication(sys.argv)
    ex = Model_GUI(app)
    ex.setWindowTitle('window')
    ex.show()
    sys.exit(app.exec_( ))


if __name__ == '__main__':
    main()

但是当我执行它时,我在 QWidget 中没有图像(在中间)。

如果我用 ex = graph() 替换 ex = Model_GUI(app),我有正确的期望:

我不明白为什么当我单独使用 QWidget 时图像设置正确,但当我将它嵌入 QMainWindow 时图像设置不正确?

QWidgets 只有在它们是顶级小部件时才使用它们的 QPalette.Window 角色(如 "windows"),否则使用父背景,除非 autoFillBackground 属性 (默认情况下为假)为真。

只需在小部件初始化中设置属性:

self.setAutoFillBackground(True)