【问题标题】:PyQt5 signal communication errorPyQt5信号通讯错误
【发布时间】:2016-12-19 07:19:54
【问题描述】:

我遇到以下问题需要您的帮助。 我有两个 Python 文件 Main.py 和 Module.py,它们需要使用 PyQt5 信号进行通信。代码如下:

Main.py

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from MyGUI import main_window_GUI

from Modules import Module.py

class MainWindow(QMainWindow, main_window_GUI.Ui_main_window):
    def __init__(self):
        QMainWindow.__init__(self)
        main_window_GUI.Ui_main_window.__init__(self)
        self.setupUI(self)

        sub_win = QMdiSubWindow()
        sub_win.setWidget(Module.moduleWindow())
        self.mdi.addSubWindow(sub_win)

        # this part reports error saying:
        # 'PyQt5.QtCore.pyqtSignal' object has no attribute 'connect'
        Module.moduleWindow.my_signal.connect(self.do_something)

    def do_something(self):
        pass

Module.py

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from MyGUI import module_window_GUI

class moduleWindow(QMainWindow, module_window_GUI.Ui_module_window):
    my_signal = pyqtSignal()
    def __init__(self):
        QMainWindow.__init__(self)
        module_window_GUI.Ui_module_window.__init__(self)
        self.setupUI(self)

        # the rest is not important

    # what is important is th following function
    def closeEvent(self, event):
        # when the user closes this subwindow signal needs to
        # be emitted so that the MainWindow class knows that
        # it's been closed.
        self.my_signal.emit()
        event.accept()

我们非常欢迎任何形式的帮助。提前致谢。

【问题讨论】:

    标签: python python-3.x signals-slots pyqt5 qmdiarea


    【解决方案1】:

    您需要连接来自moduleWindow 类实例的信号,而不是来自类本身:

    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    
    from MyGUI import main_window_GUI
    
    from Modules import Module
    
    class MainWindow(QMainWindow, main_window_GUI.Ui_main_window):
        def __init__(self):
            QMainWindow.__init__(self)
            main_window_GUI.Ui_main_window.__init__(self)
            self.setupUI(self)
    
            sub_win = QMdiSubWindow()
            module_window = Module.moduleWindow()
            sub_win.setWidget(module_window)
            self.mdi.addSubWindow(sub_win)
    
            module_window.my_signal.connect(self.do_something)
    
        @pyqtSlot()
        def do_something(self):
            pass
    

    我还建议使用 pyqtSlot 来装饰 do_something 方法,如 documentation 中所述

    【讨论】:

    • 我已经尝试过了,这次我没有收到任何错误,但是发出信号时 do_something 函数没有被执行。有什么建议?谢谢丹尼尔。
    • closeEvent 正在执行吗?
    • 您还需要保留对moduleWindow实例的引用。
    猜你喜欢
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多