当一个模块具有信号,而另一个模块需要传递插槽和参数时,避免循环导入

2024-04-24 15:15:14 发布

您现在位置:Python中文网/ 问答频道 /正文

mouseClickEvent位于ViewBoxCustom.py中,单击场景时正确触发。compute_spc_mapSPCanalyse.py中,ViewBoxCustom.py不导入它,因为这样会进行循环导入。我知道,但我想避免。你知道吗

来自ViewBoxCustom的片段

from SPCanalyse import MainWindow #This import should not exist
def mouseClickEvent(self, ev):
    elif ev.button() == QtCore.Qt.LeftButton:
        ev.accept()
        # The following line does not work because MainWindow is **NOT** imported 
        MainWindow.compute_spc_map(ev.pos().x(), ev.pos().y())

来自SPCanalyse的片段。SPCanalyse导入ViewBoxCustom以便访问函数并生成应用程序功能

from ViewBoxCustom import MultiRoiViewBox # MultiRoiViewBox contains mouseClickEvent
def compute_spc_map(self, x, y):
    if not self.preprocessed_frames == None:
        self.image = fj.get_correlation_map(y, x, self.preprocessed_frames)

我不能把compute_spc_map放在ViewBoxCustom中,因为preprocessed_frames是在SPCanalyse中生成和使用的变量

我想把ViewBoxCustom中的mouseClickEventSPCanalyse中的compute_spc_map连接起来,在SPCanalyse中执行以下操作可能会有用

from ViewBoxCustom import MultiRoiViewBox
self.vb = MultiRoiViewBox(lockAspect=True,enableMenu=True)
self.vb.mouseClickEvent.connect(self.compute_spc_map)

遗憾的是mouseClickEvent没有属性“connect”


Tags: frompyimportselfmapnotcomputeev
1条回答
网友
1楼 · 发布于 2024-04-24 15:15:14

看起来您正试图从子小部件(即ViewBoxCustomMainWindow的子部件)调用父小部件上的方法。您通常不想这样做,因为它限制了子窗口小部件的灵活性,并且可能导致循环依赖,就像您在这里遇到的那样,当子窗口小部件没有理由依赖于父窗口小部件时。你知道吗

这里使用的一个好的设计模式是,子部件发出一个Signal,父部件连接到该Signal,并使用它触发函数的调用(与直接调用函数的子部件相反)。你知道吗

就你而言:

class ViewBoxCustom(...)
    clicked = QtCore.pyqtSignal(int, int)

    def mouseClickEvent(self, ev):
        if ev.button() == QtCore.Qt.LeftButton:
            ev.accept()
            self.clicked.emit(ev.pos().x(), ev.pos().y())


class MainWindow(QtGui.QMainWindow):

    def __init__(...)
        ...
        self.vbc = ViewBoxCustom(...)
        self.vbc.clicked.connect(self.on_vbc_clicked)

    @QtCore.pyqtSlot(int, int)
    def on_vbc_clicked(self, x, y):
        self.compute_spec_map(x, y)

ViewBoxCustom没有理由导入或了解MainWindow的任何信息。你知道吗

相关问题 更多 >