我如何将 QPalette 的特定颜色角色的颜色设置为 PyQT5 中另一个 QPalette 颜色角色的颜色?

How would I set a specific color role's color of a QPalette to that of another QPalette's color role's color in PyQT5?

我手头有两个小部件,其中一个是 bg 颜色,我想将其设置为另一个的文本颜色。浏览完文档后,我找不到任何方法可以从调色板中生成特定颜色角色的颜色。

就相关性而言最接近的方法只是 returns QBrush QPalette.colorRole,我看不出它在这里有什么帮助。

假设我有一些形式

widget1 = QWidget()
palette1 = widget1.palette()
palette1.setColor(QPalette.Text, QColor('#FFAABBCC'))
widget1.setPalette(palette1)

widget2 = QWigdet()
palette2 = widget2.palette()
palette2.setColor(widget1s text color) #assume this is what the command tries to do

我想要一种方法来设置 palette2QPalette.Base 颜色角色,例如,设置为与 palette1QPalette.Text 相同的颜色] 角色。我该怎么做呢?

虽然QPalette接受QColors,但它的作用都是基于QBrush;除非画笔使用渐变或图像,否则画笔 color() 将 return 一个有效的 QColor。

设置另一个角色的颜色就像setColor(role, color)一样简单。

因为你已经在使用调色板,所以没有必要通过颜色,你可以直接分配原始画笔 setBrush(role, brush):

widget1 = QWidget()
palette1 = widget1.palette()
palette1.setColor(QPalette.Text, QColor('#FFAABBCC'))
widget1.setPalette(palette1)

widget2 = QWigdet()
palette2 = widget2.palette()
palette2.setBrush(QPalette.Base, palette1.brush(QPalette.Text))
# alternatively
palette2.setBrush(QPalette.Base, palette1.text())

widget2.setPalette(palette2)

直接 getter 函数(如 text()window())总是 return QBrush 并且它们是当前 [=] brush(role) 的快捷方式33=]颜色组。每当你需要指定不同的颜色组时,你必须使用适当的 brush()/color()setBrush()/setColor() 接受组的函数,否则使用 setCurrentColorGroup() 在此之前,如果您需要对同一组进行多次调用。