PyQt5 Python 中的程序设置是如何保存的?

我有一个可以选择主题的桌面程序。如何保存用户的选择?


def Dark_Blue_Theme(self):

    style = open('themes/darkblue.css' , 'r')

    style = style.read()

    self.setStyleSheet(style)


def Dark_Gray_Theme(self):

    style = open('themes/darkgray.css' , 'r')

    style = style.read()

    self.setStyleSheet(style)


def Dark_Orange_Theme(self):

    style = open('themes/darkorange.css' , 'r')

    style = style.read()

    self.setStyleSheet(style)


def QDark_Theme(self):

    style = open('themes/qdark.css' , 'r')

    style = style.read()

    self.setStyleSheet(style)


猛跑小猪
浏览 90回答 1
1回答

ITMISS

逻辑是使用 QSettings 保存选定的主题,然后在程序开头使用它来加载主题:import osfrom PyQt5 import QtCore, QtGui, QtWidgetsCURRENT_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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python