[英]How are the program settings saved in PyQt5 Python?
I have a desktop program with a choice of theme.我有一个可以选择主题的桌面程序。 How do I save a user's choice?
如何保存用户的选择?
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)
The logic is to use QSettings to save the selected theme and then use it at the beginning of the program to load the theme:逻辑是使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.