Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 327
Kupnu4 Avatar asked Oct 21 '25 08:10

Kupnu4


1 Answers

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:

enter image description here

like image 142
Jean-Sébastien Avatar answered Oct 22 '25 21:10

Jean-Sébastien