Search code examples
pythonpysidebackground-colorqtstylesheetsqscrollarea

Pyside: setting the background color for QScrollArea


I am making a scroll area, but I would like to change the color of the area contained within the scroll area. I tried using a stylesheet, but that ended up changing the colors of all the widgets I added inside the scroll area.

Is there any way to change the color without using stylesheets?

container = QtWidgets.QWidget()
self.list_layout = QtWidgets.QVBoxLayout(spacing=1, margin=2)

container.setLayout(self.list_layout)
scroll = QtWidgets.QScrollArea()
scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
scroll.setWidgetResizable(True)
scroll.setWidget(container)
scroll.setStyleSheet('background-color: #D8D8D8')

grid_layout.addWidget(scroll, 2, 0, 1, -1)

Solution

  • You just need to specify which classes of widget to apply the stylesheet rule to:

    scroll.setStyleSheet('QScrollArea {background-color: #D8D8D8}')
    

    Or, to be even more specific, use an object-name:

    scroll.setObjectName('myscrollarea')
    scroll.setStyleSheet('#myscrollarea {background-color: #D8D8D8}')
    

    For a complete list of qss selectors, see the Style Sheet Reference.