简体   繁体   中英

How to set background color to entire widget with stylesheet in PySide

I am trying to set a background color of a widget, but it only applies to widget's children. The code below is a simple representation of the real app structure. I'd like testWidget to be entirely red, which is 100x100 pixel rectangle due to it's size, but for some reason only the button is red.

from PySide import QtGui


class Widget(QtGui.QWidget):
def __init__(self):
    QtGui.QWidget.__init__(self)

    mainLayout = QtGui.QVBoxLayout(self)

    testWidget = QtGui.QWidget()
    testWidget.setFixedSize(100,100)

    testWidget.setStyleSheet('background-color: red;')
    testLayout = QtGui.QVBoxLayout()

    testWidget.setLayout(testLayout)


    but = QtGui.QPushButton('TEST')
    but.setFixedSize(20,20)
    testLayout.addWidget(but)

    mainLayout.addWidget(testWidget)

w = Widget()
w.show()

By default, a QWidget does not fill its background. You can either use a QFrame instead or setting the WA_StyledBackground attribute of the QWidget to True as said here : PySide: QWidget does not draw background color .

To apply the style sheet only to the container, and not to its children, the container widget can be named and the style sheet can specifically be applied to it by referring to its name.

Below is a MWE, derived from your code, that shows how it can be done using a QFrame instead of a QWidget :

from PySide import QtGui
import sys


class Widget(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        mainLayout = QtGui.QVBoxLayout(self)

        testWidget = QtGui.QFrame()
        testWidget.setFixedSize(100,100)
        testWidget.setObjectName("myWidget")
        testWidget.setStyleSheet("#myWidget {background-color:red;}") 

        testLayout = QtGui.QVBoxLayout()

        testWidget.setLayout(testLayout)

        but = QtGui.QPushButton('TEST')
        testLayout.addWidget(but)

        mainLayout.addWidget(testWidget)


if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    instance_1 = Widget()
    instance_1.show()
    sys.exit(app.exec_())

which results in:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM