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

问题描述 投票:5回答:1

我的情况:我有一个设置样式表的小部件。该样式表可能包含也可能不包含颜色设置。我想更改小部件的颜色,但是我不能只做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_())

根据this warning on the autoFillBackground method,使用盒子的托盘不起作用,>

警告:请谨慎使用此属性和Qt样式床单。当小部件的样式表具有有效的背景或border-image,此属性会自动禁用。

我的情况:我有一个设置了样式表的小部件。该样式表可能包含也可能不包含颜色设置。我想更改小部件的颜色,但是我不能只做widget.setStyleSheet(“ ...

python qt pyside qtstylesheets
1个回答
7
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.