# PyQt5 的解耦结构

代码分为如下所示的四个模块,其中 core 是各种计算服务、events 是全局事件总线、presenters 是负责接收事件 / 发射事件的协调器、views 是各子视图、主视图。

decoupling

# pyqtgraph 兼容问题

pyqtgraph(import pyqtgraph as pg)嵌入到 Pyside6 的 Widget 中无法正常显示,但是使用 PyQt5 则可正常显示

pyqtgraph

# 父类继承

例子说明:

  • MyDialog 类:这是一个对话框类,构造函数中调用了 super()._init_(parent) , 将 parent 传递给父类 QDialog 。这使得对话框知道它的父级是哪个窗口。
  • MainWindow 类:这是主窗口类,包含一个按钮。当按钮被点击时,会创建一个 MyDialog 实例,并将 self (即 MainWindow 的实例) 作为父级传递。
  • 父子关系:由于 MyDialog 的父级是 MainWindow, 当主窗口关闭时,对话框也会自动关闭。这是 parent 参数的一个重要作用,帮助管理控件的生命周期。
  • 通过这个例子,可以看到 parent 参数在控件层次结构中的重要性,以及它如何影响控件的行为。
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QVBoxLayout, QLabel

class MyDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)  # 设置父级为 MainWindow
        self.setWindowTitle("对话框")
        layout = QVBoxLayout()
        layout.addWidget(QLabel("这是一个对话框"))
        self.setLayout(layout)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主窗口")
        self.setGeometry(100, 100, 300, 200)

        self.button = QPushButton("打开对话框", self)
        self.button.clicked.connect(self.open_dialog)
        self.setCentralWidget(self.button)

    def open_dialog(self):
        dialog = MyDialog(self)  # 将 MainWindow 作为父级传递
        dialog.exec_()  # 显示对话框

if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

# 本地库的解析

现有一名为 modules(后来才改名的,一开始叫 mokuaihua)的本地发开库文件结构如下,其中 app.py 是调用该库启动界面的程序。

C:.
│  app.py
│
└─modules
    │  constants.py
    │  __init__.py
    │
    ├─core
    │      celestial_service.py
    │      location_service.py
    │      spectrum_service.py
    │      time_service.py
    │      __init__.py
    │
    ├─events
    │      evetns.py
    │      __init__.py
    │
    ├─models
    │      celestial_model.py
    │      map.txt
    │      __init__.py
    │
    ├─presenters
    │      main_presenter.py
    │      __init__.py
    │
    └─views
            azalt_view.py
            celestial_table.py
            controls_view.py
            main_window.py
            sky_view.py
            spectrum_view.py
            waterfall_view.py
            __init__.py
  • 在 models 目录下加上 __init__.pycelestial_model 文件才能被 vscode 正确解析为库

vscode

  • 运行时一直提示 “ImportError: attempted relative import beyond top-level package”,如下图,这是因为在 Python 中,相对导入(使用..)只能在包内部使用,且不能超出顶级包的边界(from ..xx.xx import xx),由于运行 app.py 时,app.py 在 modules 里面,因此报错,放到 modules 外面一层运行就没这个错误了

vscode2

  • 加入 __init__.py 文件后,调用时应从如下的直接调用名字

vscode3

​ 改为加点 (.) 调用

vscode4

参考

# 加入终端

使用 xterm 框架来嵌入 ssh 操作界面

xterm.css 和 xterm.js 文件的下载

cdn.jsdelivr.net/npm/xterm@4.19.0/css/xterm.css

cdn.jsdelivr.net/npm/xterm@4.19.0/lib/xterm.js

unpkg.com/xterm@5.3.0/css/xterm.css

参考