PyQt5:如何“收集”或“接收”发出的信号?

Cpt*_*azy 1 python signals-slots pyqt5

在我的代码中,我在 2 个单独的文件中有 2 个类。我有一个信号testSignal,一个按钮pushButton,我像这样连接了按钮:

testSignal = QtCore.pyqtSignal()

pushButton.pressed.connect(buttonPressed)

def buttonPressed(self):
    testSignal.emit()
Run Code Online (Sandbox Code Playgroud)

现在我想做的是“接收”类/文件中发出的信号,但我对 emit() 的实际工作原理有些一无所知。有谁有关于emit()函数指南的链接或者可以以某种方式提供帮助吗?

谢谢

mus*_*nte 5

[Py]Qt 信号必须在类级别声明,因为它们仅在创建新类实例时才变为“活动”。另外,它们只能用于从 QObject 继承的类(包括 QWidget 子类),并且将它们与标准 pythonobject类一起使用将不起作用

class SomeWindow(QtWidgets.QWidget):
    testSignal = QtCore.pyqtSignal()
    def __init__(self):
        super().__init__()
        # ...
        pushButton.pressed.connect(self.buttonPressed)
        # connect the custom signal with an *instance method*
        self.testSignal.connect(self.someInstanceFunction)

    def buttonPressed(self):
        # emit the signal
        self.testSignal.emit()

    def someInstanceFunction(self):
        print('hello from the instance!')


def someAnonymousFunction():
    print('hello from outside!')


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = SomeWindow()
    # connect the signal with an anonymous function
    window.testSignal.connect(someAnonymousFunction)
    sys.exit(app.exec_())

Run Code Online (Sandbox Code Playgroud)

显然,上面的示例没有多大意义,因为自定义信号通常用于在(可能不同的)类的实例之间进行通信,但这只是为了解释目的。另外,您可以“连接”信号(只要它们的签名兼容):

class SomeWindow(QtWidgets.QWidget):
    testSignal = QtCore.pyqtSignal()
    def __init__(self):
        super().__init__()
        # ...
        # emit the testSignal when the button emits its pressed signal
        pushButton.pressed.connect(self.testSignal)
        self.testSignal.connect(self.someInstanceFunction)

    # ...
Run Code Online (Sandbox Code Playgroud)

请注意,如果您想在用户单击按钮时执行某些操作,则应该使用clicked(),而不是pressed(),并且区别非常重要:通常的约定是,仅当用户按下释放鼠标按钮时才认为按钮被单击在按钮区域内,这样可以避免在按钮区域释放鼠标按钮时发生“点击” 。如果连接到pressed(),只要按下鼠标按钮就会发出信号这不被视为标准行为。