Set background color of layout
Asked Answered
F

1

12

As the layout object has no attribute ".setStyleSheet()", how can one set the background color for a given layout?

As a visual explanation, I can set both the label and the button background color, but not the entire layout, which includes the spacer.

enter image description here

Programatically, I'm organizing some information in horizontal layouts and displaying them in a frame. I would like to alternate background colors for each loop.

for param_name in parameters:
    hlayouts.append(QtGui.QHBoxLayout())
    labels.append(QtGui.QLabel("%s"%param_name))
    sliders.append(QtGui.QSpacerItem(10,10,hPolicy=QtGui.QSizePolicy.Expanding))
    spins.append(QtGui.QDoubleSpinBox())

    spins[index].setValue(float(values.get(param_name)))
    labels[index].setStyleSheet("background-color:black;")
    spins[index].setStyleSheet("background-color:black;")

    hlayouts[index].addWidget(labels[index])
    hlayouts[index].addItem(sliders[index])
    hlayouts[index].addWidget(spins[index])

    index += 1

vlayout = QtGui.QVBoxLayout()
for i in range(len(hlayouts)):
    vlayout.addLayout(hlayouts[i])
Freightage answered 16/12, 2014 at 8:44 Comment(0)
M
15

You could just add set the layout on an empty QWidget and set the StyleSheet on this widget.

for index, param_name in enumerate(parameters):
    container = QtGui.QWidget(self)
    layout = QtGui.QHBoxLayout(container )

    hlayouts.append(container)
    labels.append(QtGui.QLabel("%s"%param_name))
    sliders.append(QtGui.QSpacerItem(10,10,hPolicy=QtGui.QSizePolicy.Expanding))
    spins.append(QtGui.QDoubleSpinBox())

    spins[index].setValue(float(values.get(param_name)))
    container.setStyleSheet("background-color:black;")

    layout.addWidget(labels[index])
    layout.addItem(sliders[index])
    layout.addWidget(spins[index])


vlayout = QtGui.QVBoxLayout(self)
for widget in hlayouts:
    vlayout.addWidget(widget)
Mo answered 16/12, 2014 at 9:0 Comment(4)
that does not set each layout of the loop, it sets the entire frameFreightage
you cant use .addWidget() on a widget, which is the containerFreightage
And I don't. I use addWidget on the layout.Mo
sorry didnt see some of the differences in your codeFreightage

© 2022 - 2024 — McMap. All rights reserved.