如何将图像应用于小部件背景(叠加)

1 投票
1 回答
1739 浏览
提问于 2025-04-18 07:26

我想给像QListWidget或者QWidget这样的控件设置一个背景图片。这里有个想法:enter image description hereenter image description here

理想情况下,当控件的大小变化时,背景图片也能自动调整大小。有没有什么好办法可以做到这一点呢?

后续编辑:

这是一个对话框的截图,里面实现了Salvatore的建议。如果使用的背景图片是PNG格式,那么可以通过调整它的透明度来控制它的可见程度(让它变得更淡)。我很喜欢这个效果……谢谢!

enter image description here


from PyQt4 import QtGui, QtCore

class MyApp(object):    
    def __init__(self):
        super(MyApp, self).__init__()                
        self.mainWidget = QtGui.QWidget()
        self.mainLayout = QtGui.QVBoxLayout()
        self.mainWidget.setLayout(self.mainLayout)

        self.hLayout = QtGui.QHBoxLayout()
        self.mainLayout.insertLayout(0, self.hLayout)
        self.listA=QtGui.QListWidget()
        for i in range(3):
            self.listA.addItem('Item '+str(i))
        self.hLayout.addWidget(self.listA)

        self.buttonGroupbox = QtGui.QGroupBox()
        self.buttonlayout = QtGui.QVBoxLayout()
        self.buttonGroupbox.setLayout(self.buttonlayout)

        okButton = QtGui.QPushButton('OK')
        self.buttonlayout.addWidget(okButton)

        self.mainLayout.addWidget(self.buttonGroupbox)
        self.mainWidget.show()
        sys.exit(app.exec_())

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    MyApp()

1 个回答

1

也许你可以给目标小部件设置一个样式表:

self.listA.setStyleSheet("""
    color: white; 
    background-image: url(./your_image.jpg);
    background-attachment: scroll;
""");

但是用这段代码的话,你的图片不会自动调整大小。

撰写回答