Skip to content

Commit bbbc41a

Browse files
committed
优化代码
1 parent 03d641b commit bbbc41a

5 files changed

Lines changed: 617 additions & 303 deletions

File tree

app/core/app_init.py

Lines changed: 50 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,30 +8,31 @@
88
from app.tools.variable import APP_INIT_DELAY
99
from app.core.font_manager import apply_font_settings
1010
from app.core.window_manager import WindowManager
11+
from app.core.utils import safe_execute
1112

1213

1314
class AppInitializer:
1415
"""应用程序初始化器,负责协调所有初始化任务"""
1516

16-
def __init__(self, window_manager: WindowManager):
17+
def __init__(self, window_manager: WindowManager) -> None:
1718
"""初始化应用初始化器
1819
1920
Args:
2021
window_manager: 窗口管理器实例
2122
"""
2223
self.window_manager = window_manager
2324

24-
def initialize(self):
25+
def initialize(self) -> None:
2526
"""初始化应用程序"""
2627
self._manage_settings_file()
2728
self._schedule_initialization_tasks()
2829
logger.debug("应用初始化调度已启动,主窗口将在延迟后创建")
2930

30-
def _manage_settings_file(self):
31+
def _manage_settings_file(self) -> None:
3132
"""管理设置文件,确保其存在且完整"""
3233
manage_settings_file()
3334

34-
def _schedule_initialization_tasks(self):
35+
def _schedule_initialization_tasks(self) -> None:
3536
"""调度所有初始化任务"""
3637
self._load_theme()
3738
self._load_theme_color()
@@ -40,48 +41,70 @@ def _schedule_initialization_tasks(self):
4041
self._create_main_window()
4142
self._apply_font_settings()
4243

43-
def _load_theme(self):
44+
def _load_theme(self) -> None:
4445
"""加载主题设置"""
45-
from qfluentwidgets import setTheme, Theme
46-
4746
QTimer.singleShot(
4847
APP_INIT_DELAY,
49-
lambda: (
50-
setTheme(Theme.DARK)
51-
if readme_settings_async("basic_settings", "theme") == "DARK"
52-
else (
53-
setTheme(Theme.AUTO)
54-
if readme_settings_async("basic_settings", "theme") == "AUTO"
55-
else setTheme(Theme.LIGHT)
56-
)
57-
),
48+
lambda: safe_execute(self._apply_theme, error_message="加载主题失败"),
5849
)
5950

60-
def _load_theme_color(self):
51+
def _apply_theme(self) -> None:
52+
"""应用主题设置"""
53+
from qfluentwidgets import setTheme, Theme
54+
55+
theme = readme_settings_async("basic_settings", "theme")
56+
if theme == "DARK":
57+
setTheme(Theme.DARK)
58+
elif theme == "AUTO":
59+
setTheme(Theme.AUTO)
60+
else:
61+
setTheme(Theme.LIGHT)
62+
63+
def _load_theme_color(self) -> None:
6164
"""加载主题颜色"""
6265
from qfluentwidgets import setThemeColor
6366

6467
QTimer.singleShot(
6568
APP_INIT_DELAY,
66-
lambda: setThemeColor(
67-
readme_settings_async("basic_settings", "theme_color")
69+
lambda: safe_execute(
70+
lambda: setThemeColor(
71+
readme_settings_async("basic_settings", "theme_color")
72+
),
73+
error_message="加载主题颜色失败",
6874
),
6975
)
7076

71-
def _clear_restart_record(self):
77+
def _clear_restart_record(self) -> None:
7278
"""清除重启记录"""
73-
QTimer.singleShot(APP_INIT_DELAY, lambda: remove_record("", "", "", "restart"))
79+
QTimer.singleShot(
80+
APP_INIT_DELAY,
81+
lambda: safe_execute(
82+
lambda: remove_record("", "", "", "restart"),
83+
error_message="清除重启记录失败",
84+
),
85+
)
7486

75-
def _check_updates(self):
87+
def _check_updates(self) -> None:
7688
"""检查是否需要安装更新"""
77-
QTimer.singleShot(APP_INIT_DELAY, lambda: check_for_updates_on_startup(None))
89+
QTimer.singleShot(
90+
APP_INIT_DELAY,
91+
lambda: safe_execute(
92+
lambda: check_for_updates_on_startup(None), error_message="检查更新失败"
93+
),
94+
)
7895

79-
def _create_main_window(self):
96+
def _create_main_window(self) -> None:
8097
"""创建主窗口实例(但不自动显示)"""
8198
QTimer.singleShot(
82-
APP_INIT_DELAY, lambda: self.window_manager.create_main_window()
99+
APP_INIT_DELAY,
100+
lambda: safe_execute(
101+
self.window_manager.create_main_window, error_message="创建主窗口失败"
102+
),
83103
)
84104

85-
def _apply_font_settings(self):
105+
def _apply_font_settings(self) -> None:
86106
"""应用字体设置"""
87-
QTimer.singleShot(APP_INIT_DELAY, lambda: apply_font_settings())
107+
QTimer.singleShot(
108+
APP_INIT_DELAY,
109+
lambda: safe_execute(apply_font_settings, error_message="应用字体设置失败"),
110+
)

app/core/font_manager.py

Lines changed: 73 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,89 @@
11
import os
2+
from typing import Optional
23
from PySide6.QtCore import Qt, QTimer
34
from PySide6.QtWidgets import QApplication, QWidget
45
from loguru import logger
56

67
from app.tools.settings_access import readme_settings_async
78
from app.tools.variable import FONT_APPLY_DELAY
9+
from app.core.utils import safe_execute
810

911

10-
def configure_dpi_scale():
12+
def configure_dpi_scale() -> None:
1113
"""在创建QApplication之前配置DPI缩放模式"""
1214
try:
13-
dpiScale = readme_settings_async("basic_settings", "dpiScale")
14-
if dpiScale == "Auto":
15-
QApplication.setHighDpiScaleFactorRoundingPolicy(
16-
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
17-
)
18-
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
19-
logger.debug("DPI缩放已设置为自动模式")
15+
dpi_scale = readme_settings_async("basic_settings", "dpiScale")
16+
if dpi_scale == "Auto":
17+
_set_auto_dpi()
2018
else:
21-
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
22-
os.environ["QT_SCALE_FACTOR"] = str(dpiScale)
23-
logger.debug(f"DPI缩放已设置为{dpiScale}倍")
19+
_set_manual_dpi(dpi_scale)
2420
except Exception as e:
2521
logger.warning(f"读取DPI设置失败,使用默认设置: {e}")
26-
QApplication.setHighDpiScaleFactorRoundingPolicy(
27-
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
28-
)
29-
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
22+
_set_auto_dpi()
3023

3124

32-
def apply_font_settings():
25+
def _set_auto_dpi() -> None:
26+
"""设置自动DPI缩放"""
27+
QApplication.setHighDpiScaleFactorRoundingPolicy(
28+
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
29+
)
30+
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
31+
logger.debug("DPI缩放已设置为自动模式")
32+
33+
34+
def _set_manual_dpi(scale: str) -> None:
35+
"""设置手动DPI缩放
36+
37+
Args:
38+
scale: 缩放倍数
39+
"""
40+
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
41+
os.environ["QT_SCALE_FACTOR"] = str(scale)
42+
logger.debug(f"DPI缩放已设置为{scale}倍")
43+
44+
45+
def apply_font_settings() -> None:
3346
"""应用字体设置 - 优化版本,使用字体管理器异步加载"""
3447
font_family = readme_settings_async("basic_settings", "font")
3548

3649
from qfluentwidgets import setFontFamilies
3750

3851
setFontFamilies([font_family])
39-
QTimer.singleShot(FONT_APPLY_DELAY, lambda: apply_font_to_application(font_family))
52+
QTimer.singleShot(
53+
FONT_APPLY_DELAY,
54+
lambda: safe_execute(
55+
apply_font_to_application, font_family, error_message="应用字体失败"
56+
),
57+
)
4058

4159

42-
def apply_font_to_application(font_family: str):
60+
def apply_font_to_application(font_family: str) -> None:
4361
"""应用字体设置到整个应用程序,优化版本使用字体管理器
4462
4563
Args:
46-
font_family (str): 字体家族名称
64+
font_family: 字体家族名称
4765
"""
48-
try:
49-
current_font = QApplication.font()
50-
app_font = current_font
51-
app_font.setFamily(font_family)
52-
widgets_updated = 0
53-
widgets_skipped = 0
54-
for widget in QApplication.allWidgets():
55-
if isinstance(widget, QWidget):
56-
if update_widget_fonts(widget, app_font, font_family):
57-
widgets_updated += 1
58-
else:
59-
widgets_skipped += 1
60-
logger.debug(
61-
f"已应用字体: {font_family}, 更新了{widgets_updated}个控件字体, 跳过了{widgets_skipped}个已有相同字体的控件"
62-
)
63-
except Exception as e:
64-
logger.error(f"应用字体失败: {e}")
66+
current_font = QApplication.font()
67+
app_font = current_font
68+
app_font.setFamily(font_family)
6569

70+
widgets_updated = 0
71+
widgets_skipped = 0
72+
73+
for widget in QApplication.allWidgets():
74+
if isinstance(widget, QWidget):
75+
if update_widget_fonts(widget, app_font, font_family):
76+
widgets_updated += 1
77+
else:
78+
widgets_skipped += 1
6679

67-
def update_widget_fonts(widget: QWidget, font, font_family: str) -> bool:
80+
logger.debug(
81+
f"已应用字体: {font_family}, 更新了{widgets_updated}个控件字体, "
82+
f"跳过了{widgets_skipped}个已有相同字体的控件"
83+
)
84+
85+
86+
def update_widget_fonts(widget: Optional[QWidget], font, font_family: str) -> bool:
6887
"""更新控件及其子控件的字体,优化版本减少内存占用,特别处理ComboBox等控件
6988
7089
Args:
@@ -78,27 +97,22 @@ def update_widget_fonts(widget: QWidget, font, font_family: str) -> bool:
7897
if widget is None:
7998
return False
8099

81-
try:
82-
if not hasattr(widget, "font") or not hasattr(widget, "setFont"):
83-
return False
84-
current_widget_font = widget.font()
85-
if current_widget_font.family() == font_family:
86-
updated = False
87-
else:
88-
new_font = font
89-
new_font.setBold(current_widget_font.bold())
90-
new_font.setItalic(current_widget_font.italic())
91-
widget.setFont(new_font)
92-
updated = True
100+
if not hasattr(widget, "font") or not hasattr(widget, "setFont"):
101+
return False
93102

94-
if isinstance(widget, QWidget):
95-
children = widget.children()
96-
for child in children:
97-
if isinstance(child, QWidget):
98-
child_updated = update_widget_fonts(child, font, font_family)
99-
if child_updated:
100-
updated = True
101-
return updated
102-
except Exception as e:
103-
logger.exception("更新控件字体时发生异常: {}", e)
103+
current_widget_font = widget.font()
104+
if current_widget_font.family() == font_family:
104105
return False
106+
107+
new_font = font
108+
new_font.setBold(current_widget_font.bold())
109+
new_font.setItalic(current_widget_font.italic())
110+
widget.setFont(new_font)
111+
112+
if isinstance(widget, QWidget):
113+
children = widget.children()
114+
for child in children:
115+
if isinstance(child, QWidget):
116+
update_widget_fonts(child, font, font_family)
117+
118+
return True

0 commit comments

Comments
 (0)