为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

猛跑小猪 2023-09-02 16:24:17
我有一个可以选择主题的桌面程序。如何保存用户的选择?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)
查看完整描述

1 回答

?
ITMISS

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


查看完整回答
反对 回复 2023-09-02
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信