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

问题描述 投票:0回答:1

我正在尝试在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中没有图像(在中间)。

enter image description here

如果我将ex = Model_GUI(app)替换为ex = graph(),则表示正确的期望:

enter image description here

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

python image background pyqt pyqt5
1个回答
0
投票

QWidget仅当它们是顶级窗口小部件时才使用它们的QPalette.Window角色(如在Windows中),否则,除非autoFillBackground属性(默认为false)为true,否则将使用父背景。

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

autoFillBackground
© www.soinside.com 2019 - 2024. All rights reserved.