1 回答
TA贡献1871条经验 获得超8个赞
逻辑是使用 QSettings 保存选定的主题,然后在程序开头使用它来加载主题:
import os
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
THEME_DIR = os.path.join(CURRENT_DIR, "themes")
DEFAULT_THEME = "qdark"
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self._theme = ""
self.restore_settings()
self.load_theme()
themes_menu = self.menuBar().addMenu(self.tr("Themes"))
it = QtCore.QDirIterator(THEME_DIR, ["*.css"])
group = QtWidgets.QActionGroup(self)
group.triggered.connect(self.handle_theme_triggered)
while it.hasNext():
it.next()
fi = it.fileInfo()
action = QtWidgets.QAction(fi.baseName(), self)
action.setCheckable(True)
group.addAction(action)
themes_menu.addAction(action)
if fi.baseName() == self.theme:
action.setChecked(True)
def handle_theme_triggered(self, action):
self._theme = action.text()
self.load_theme()
self.save_settings()
@property
def theme(self):
return self._theme
def save_settings(self):
settings = QtCore.QSettings()
settings.setValue("theme", self.theme)
def restore_settings(self):
settings = QtCore.QSettings()
theme = settings.value("theme")
if theme:
self._theme = theme
else:
self._theme = DEFAULT_THEME
self.save_settings()
def load_theme(self):
if self.theme:
theme_file = os.path.join(THEME_DIR, self.theme + ".css")
with open(theme_file) as f:
style = f.read()
self.setStyleSheet(style)
def closeEvent(self, event):
self.save_settings()
super().closeEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec())
├── main.py
└── themes
├── darkblue.css
├── darkgray.css
├── darkorange.css
└── qdark.css
添加回答
举报