如何在PySide6中应用Qt6.5深色模式新实现方式?
PySide6 中 Qt6.5 Windows 11 深色模式实现方案
旧版本实现方式(Qt6.5之前)
在Qt6.5推出原生Windows11深色模式支持前,通常通过手动设置调色板或加载自定义QSS样式来实现深色主题:
from PySide6.QtWidgets import QApplication, QMainWindow from PySide6.QtGui import QPalette, QColor app = QApplication([]) # 手动配置深色调色板 palette = QPalette() palette.setColor(QPalette.Window, QColor(53, 53, 53)) palette.setColor(QPalette.WindowText, QColor(255, 255, 255)) palette.setColor(QPalette.Base, QColor(25, 25, 25)) palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) palette.setColor(QPalette.Text, QColor(255, 255, 255)) palette.setColor(QPalette.Button, QColor(53, 53, 53)) palette.setColor(QPalette.ButtonText, QColor(255, 255, 255)) app.setPalette(palette) window = QMainWindow() window.show() app.exec()
Qt6.5+ Windows11 原生深色模式实现
Qt6.5针对Windows11添加了系统级深色模式支持,无需手动配置大量样式,只需确保使用PySide6 6.5及以上版本,即可实现两种方案:
方案1:自动跟随系统主题(推荐)
直接启用Windows原生样式,应用会自动同步系统的深色/浅色模式切换,包括原生标题栏和控件样式的适配:
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton app = QApplication([]) # 启用Windows原生样式,自动适配系统主题 app.setStyle("windowsvista") # 创建测试窗口 window = QMainWindow() window.setGeometry(100, 100, 400, 300) btn = QPushButton("测试按钮", window) btn.move(150, 120) window.show() app.exec()
方案2:强制深色模式
如果不需要跟随系统,可直接设置系统深色调色板:
from PySide6.QtWidgets import QApplication, QMainWindow from PySide6.QtGui import QPalette from PySide6.QtCore import Qt app = QApplication([]) # 强制应用深色调色板 dark_palette = QPalette() dark_palette.setColor(QPalette.Window, Qt.GlobalColor.darkGray) dark_palette.setColor(QPalette.WindowText, Qt.GlobalColor.white) dark_palette.setColor(QPalette.Base, Qt.GlobalColor.black) dark_palette.setColor(QPalette.Text, Qt.GlobalColor.white) dark_palette.setColor(QPalette.Button, Qt.GlobalColor.darkGray) dark_palette.setColor(QPalette.ButtonText, Qt.GlobalColor.white) app.setPalette(dark_palette) window = QMainWindow() window.show() app.exec()
内容的提问来源于stack exchange,提问作者emcek
相关产品推荐
相关产品推荐

