You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt明暗模式切换按钮开发求助:恢复默认Palette遇难题

解决Qt明暗模式切换中恢复默认Palette的问题

你的代码里切换回亮色模式时调用QApplication.setPalette("")是错误的——这个方法要求传入QPalette对象,而非字符串,所以无法正确恢复默认样式。

有两种可靠的解决方式:

方式一:提前保存默认Palette

在类初始化阶段保存应用的默认调色板,后续切换时直接复用:

  1. 在类的__init__方法中添加保存代码:
def __init__(self):
    # 其他初始化逻辑
    self.dark_mode = False
    # 保存系统默认调色板
    self.default_palette = QApplication.palette()
  1. 修改modeSwitch方法中的亮色模式切换逻辑:
if self.dark_mode:
    self.dark_mode = False
    QApplication.setPalette(self.default_palette)

方式二:直接创建默认Palette实例

如果不想提前保存,也可以直接创建一个不带参数的QPalette对象(默认会使用系统样式):

if self.dark_mode:
    self.dark_mode = False
    QApplication.setPalette(QPalette())

修改后的完整代码

def modeSwitch(self):
    if self.dark_mode:
        self.dark_mode = False
        # 二选一:使用提前保存的默认调色板,或直接创建默认实例
        QApplication.setPalette(self.default_palette)
        # QApplication.setPalette(QPalette())
    else:   
        self.dark_mode = True
        dark_palette = QPalette()
        dark_palette.setColor(QPalette.Window, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.WindowText, Qt.white)
        dark_palette.setColor(QPalette.Base, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.AlternateBase, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.ToolTipBase, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.ToolTipText, Qt.white)
        dark_palette.setColor(QPalette.Text, Qt.white)
        dark_palette.setColor(QPalette.Button, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.ButtonText, Qt.white)
        dark_palette.setColor(QPalette.BrightText, Qt.red)
        dark_palette.setColor(QPalette.Link, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.Highlight, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.HighlightedText, QColor(97, 97, 97))
        dark_palette.setColor(QPalette.Active, QPalette.Button, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.darkGray)
        dark_palette.setColor(QPalette.Disabled, QPalette.WindowText, Qt.darkGray)
        dark_palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
        dark_palette.setColor(QPalette.Disabled, QPalette.Light, QColor(35, 35, 35))
        QApplication.setPalette(dark_palette)

内容的提问来源于stack exchange,提问作者Navis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 12:01:02