我可以成功创建一个新的调色板,并在启动时将其设置为QApplication。但是,一旦应用程序运行,我就无法再更改调色板的颜色。如果用户选择特定主题,我想更改按钮的颜色。当前在启动时工作的代码如下:
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Window, QtGui.QColor(3, 18, 14))
palette.setColor(QtGui.QPalette.Base, QtGui.QColor(15, 15, 15))
palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(53, 53, 53))
palette.setColor(QtGui.QPalette.ToolTipBase, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.Text, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53, 53, 53))
palette.setColor(QtGui.QPalette.ButtonText, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red)
palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(142, 45, 197).lighter())
palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black)
app.setPalette(palette)
如果在插槽中使用相同的调色板对象,则不会更改颜色。例如插槽中的代码:
palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53, 53, 53))
app.setPalette(palette)
有人可以让我知道我在这里失踪了吗?谢谢。
编辑:我刚刚发现它只修改了一些区域。例如,在我写的插槽中,它改变了高亮颜色,但没有改变QTab颜色(通过将颜色设置为Button来设置)。我目前的老虎机代码:
def change_theme(self):
pal = QtWidgets.QApplication.palette()
#The next line works
pal.setColor(QtGui.QPalette.Highlight, QtGui.QColor(0, 0, 128))
#The next line doesnt work. Expected it to change the Tab Widget color
#using this line.
pal.setColor(QtGui.QPalette.Button, QtGui.QColor(62, 80, 91))
QtWidgets.QApplication.setPalette(pal)
尝试设置app.setStyle('Fusion')
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QApplication
from PyQt5.QtGui import QPalette, QColor
class Window(QWidget):
def __init__(self):
super().__init__()
self.flag = False
self.button = QPushButton('change the colors of the buttons', self)
self.button.clicked.connect(self.click)
lay = QVBoxLayout(self)
lay.addWidget(self.button)
self.palette = self.palette()
self.palette.setColor(QPalette.Window, QColor(3, 18, 14))
self.palette.setColor(QPalette.Button, QColor('red'))
self.setPalette(self.palette)
def click(self):
print("click")
if not self.flag:
self.palette.setColor(QPalette.Button, QColor(62, 80, 91))
else:
self.palette.setColor(QPalette.Button, QColor(0, 0, 128))
self.setPalette(self.palette)
self.flag = not self.flag
if __name__ == '__main__':
import sys
app = QApplication([])
app.setStyle('Fusion') # <-----
w = Window()
w.show()
sys.exit(app.exec_())