My situation: I have a widget with a set of styles. This style sheet may or may not include color settings. I want to change the color of the widget, but I can’t just do widget.setStyleSheet("QWidget {background-color: %s}"% colour)it because it replaces the existing stylesheet, which I don’t want to do.
My question: What is the correct method for changing the color (in my case) of the color of the widget without erasing this widget style sheet? Is there a better way than parsing and adding to a stylesheet?
Example:
In the code below, how can I change the color box(imagining that the color of the box should change dynamically, for example, the red box when it contains an even number of elements, and green when the number is odd)?
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
box = QtGui.QComboBox(self)
box.resize(box.sizeHint())
box.setStyleSheet("""
QComboBox::drop-down {border-width: 0px;}
QComboBox::down-arrow {image: url(noimg); border-width: 0px;}
""")
box.move(50, 50)
pal = box.palette()
pal.setColor(box.backgroundRole(), QtCore.Qt.red)
box.setAutoFillBackground(True)
box.setPalette(pal)
self.setGeometry(300, 300, 250, 150)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Using a box pallet does not work, presumably in this warning by the methodautoFillBackground :
Warning. Use this property with caution in combination with Qt Style Sheets. When a widget has a style sheet with a valid background or border-image, this property is automatically disabled.
source
share