Pyside:在运行时修改小部件颜色而不覆盖样式表.

For*_*ntr 5 python qt pyside qtstylesheets

我的情况:我有一个设有样式表的小部件.该样式表可能包含也可能不包括颜色设置.我想改变小部件的颜色,但我不能这样做widget.setStyleSheet("QWidget {background-color: %s}"% colour),因为它取代了现有的样式表,我不想这样做.

我的问题:在不删除小部件样式表的情况下,更改小部件(背景,在我的情况下)颜色的正确方法是什么?有没有比解析和附加到样式表更好的方法?

例:

在下面的代码中,我如何更改颜色box(想象盒子的颜色必须动态改变;例如,当盒子包含偶数个项目时盒子是红色的,当数字是奇数时盒子是绿色的)?

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)

        #Using the palette doesn't work:
        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_())
Run Code Online (Sandbox Code Playgroud)

使用盒子的托盘不起作用,大概是根据方法的这个警告autoFillBackground:

警告:谨慎使用此属性与Qt样式表一起使用.当窗口小部件具有带有效背景或边框图像的样式表时,将自动禁用此属性.

ekh*_*oro 7

您可以使用动态属性执行此操作:

from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QLineEdit(self)
        self.edit.setProperty('warning', False)
        self.edit.setStyleSheet("""
           /* other rules go here */
           QLineEdit[warning="true"] {background-color: yellow};
           QLineEdit[warning="false"] {background-color: palette(base)};
            """)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)

    def handleButton(self):
        self.edit.setProperty(
            'warning', not self.edit.property('warning'))
        self.edit.style().unpolish(self.edit)
        self.edit.style().polish(self.edit)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)