Files
Projects/toolbox/codes/common/qss_reloader.py
2025-10-10 17:16:08 +08:00

41 lines
1.2 KiB
Python

from pathlib import Path
from PySide6.QtCore import QObject, QFileSystemWatcher
class QssReloader(QObject):
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self):
super().__init__()
self.path2objs = {}
self.watcher = QFileSystemWatcher(self)
self.watcher.fileChanged.connect(self.on_file_changed)
def register(self, qss_path: str, ui_obj):
path = str(Path(qss_path).resolve())
obj_list = self.path2objs.setdefault(path, [])
if ui_obj not in obj_list:
obj_list.append(ui_obj)
if path not in self.watcher.files():
self.watcher.addPath(path)
self.apply_one(path, ui_obj)
def on_file_changed(self, path: str):
for obj in self.path2objs.get(path, []):
self.apply_one(path, obj)
if path not in self.watcher.files():
self.watcher.addPath(path)
@staticmethod
def apply_one(path: str, obj):
qss = Path(path).read_text(encoding="utf-8")
obj.setStyleSheet(qss)
qss_reloader = QssReloader()