PyQt5 信号不会连接

PyQt5 Signal is not going to connect

所以我目前正在开发 PyQT5 GUI,我已经坚持了几个小时。 我想要 signal1 连接到 slot3 但没有任何反应。我真的很困惑。为什么无法连接到 slot3

import sys

from PyQt5 import QtCore as core
from PyQt5 import QtWidgets as widget


class MainApp(widget.QApplication):
    def __init__(self, argv):
        widget.QApplication.__init__(self, argv)
        self.window1 = Window1()
        self.window2 = Window2()
        self.window1.signal1.connect(self.window2.slot3)


class Window1(widget.QMainWindow):
    signal1 = core.pyqtSignal()
    signal2 = core.pyqtSignal()

    def __init__(self):
        widget.QMainWindow.__init__(self)
        self.slot1()
        self.show()

    def slot1(self):
        self.signal1.emit()
        print('slot1 connected')

    def slot2(self):
        print('slot2 connected')


class Window2(widget.QMainWindow):
    signal3 = core.pyqtSignal()
    signal4 = core.pyqtSignal()

    def __init__(self):
        widget.QMainWindow.__init__(self)
        self.show()

    def slot3(self):
        print('slot3 connected')

    def slot4(self):
        print('slot4 connected')


if __name__ == '__main__':
    app = MainApp(sys.argv)
    sys.exit(app.exec_())

问题是因为信号在连接前发出。在给定时刻发出的信号只会被之前连接过的插槽听到,不会通知新连接。

一种可能的解决方案是使用 QTimer:

core.QTimer.singleShot(0, self.signal1)

在代码中,QTimer.singleShot(0, ...) 在 eventloop 取得控制权后立即调用,也就是在执行同步逻辑(连接代码所在的位置)后立即调用。