certflow.views.bases.base_view 源代码
"""视图基类(重构计划阶段 1)。
提供跨视图的统一契约与**真实可复用 helper**,避免各 view 手写重复:
- ``init_ui()``:子类构造 UI 的唯一入口,基类 ``__init__`` 末尾调用一次。
- ``refresh()``:外部触发的数据刷新钩子(默认空实现)。
- ``retranslate_ui()``:语言切换后的文本刷新钩子(默认空实现),
``MainWindow`` 未来可在语言变更时广播给所有已注册视图。
- ``tr(text)`` / ``_tr(text)``:委托全局 i18n(``QApplication.instance().i18n_manager``,
与现有 ``query_view`` 读取 ``app.theme_manager`` 同约定),无则原样返回。
- ``is_dark_theme()``:集中 ``query_view._is_dark_theme`` 的重复实现。
- ``on_theme_changed(theme)``:主题切换钩子(默认空实现),供主题感知视图覆写。
非破坏性:仅定义契约与 helper,不改动任何现有视图。
"""
from __future__ import annotations
from PySide6.QtWidgets import QApplication, QWidget
[文档]
class BaseView(QWidget):
"""所有业务视图的基类。
现有视图当前在 ``__init__`` 内联构造 UI、各自实现 ``refresh`` / ``retranslate_ui``
(仅 ``settings_view`` 有 ``retranslate_ui``、仅 ``query_view`` 有 ``_is_dark_theme``)。
本类把这些散落约定收敛为统一钩子 + helper,供后续灰度迁移继承。
"""
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
# 统一入口:子类覆写 init_ui 即可,不必再手动调 super 后的构建顺序
self.init_ui()
# ============================================================
# 子类覆写钩子(默认空实现,保证可独立实例化)
# ============================================================
[文档]
def init_ui(self) -> None:
"""构造 UI。子类必须实现;基类在 ``__init__`` 末尾调用一次。"""
[文档]
def refresh(self) -> None:
"""外部触发的数据刷新(如切换流水线阶段、数据变更后)。默认空实现。"""
[文档]
def retranslate_ui(self) -> None:
"""语言切换后刷新 UI 文本。默认空实现,``MainWindow`` 可在语言变更时广播。"""
[文档]
def on_theme_changed(self, theme: str) -> None:
"""主题切换回调(``"light"`` / ``"dark"``)。默认空实现,主题感知视图覆写。"""
# ============================================================
# 真实可复用 helper(集中散落在各 view 的重复实现)
# ============================================================
[文档]
def tr(self, text: str) -> str:
"""翻译文本。
委托 ``QApplication.instance().i18n_manager.tr``(与现有视图读取
``app.theme_manager`` 的同一种全局挂载约定);找不到则原样返回。
"""
app = QApplication.instance()
i18n = getattr(app, "i18n_manager", None) if app is not None else None
if i18n is not None and hasattr(i18n, "tr"):
try:
return i18n.tr(text) # type: ignore[attr-defined]
except Exception:
return text
return text
# 别名,兼容现有视图里 ``self._tr(...)`` 的写法
_tr = tr
[文档]
def is_dark_theme(self) -> bool:
"""当前是否为深色主题(集中 ``query_view._is_dark_theme`` 的重复实现)。"""
app = QApplication.instance()
theme_manager = getattr(app, "theme_manager", None) if app is not None else None
if theme_manager is not None and hasattr(theme_manager, "current_theme"):
try:
return theme_manager.current_theme == "dark" # type: ignore[attr-defined]
except Exception:
return False
return False