PyQt signal with arguments of arbitrary type / PyQt_PyObject equivalent for new-style signals

前端 未结 2 1518
悲&欢浪女
悲&欢浪女 2020-12-11 03:40

I have an object that should signal that a value has changed by emitting a signal with the new value as an argument. The type of the value can change, and so I\'m unsure of

2条回答
  •  無奈伤痛
    2020-12-11 04:12

    I'm a beginner and this is the first question I'm attempting to answer, so apologies if I have misunderstood the question...

    The following code emits a signal that sends a custom Python object, and the slot uses that class to print "Hello World".

    import sys
    from PyQt4.QtCore import pyqtSignal, QObject
    
    class NativePythonObject(object):
        def __init__(self, message):
            self.message = message
    
        def printMessage(self):
            print(self.message)
            sys.exit()
    
    class SignalEmitter(QObject):
        theSignal = pyqtSignal(NativePythonObject)
    
        def __init__(self, toBeSent, parent=None):
            super(SignalEmitter, self).__init__(parent)
            self.toBeSent = toBeSent
    
        def emitSignal(self):
            self.theSignal.emit(toBeSent)
    
    class ClassWithSlot(object):
        def __init__(self, signalEmitter):
            self.signalEmitter = signalEmitter
            self.signalEmitter.theSignal.connect(self.theSlot)
    
        def theSlot(self, ourNativePythonType):
            ourNativePythonType.printMessage()
    
    if __name__ == "__main__":
        toBeSent = NativePythonObject("Hello World")
        signalEmitter = SignalEmitter(toBeSent)
        classWithSlot = ClassWithSlot(signalEmitter)
        signalEmitter.emitSignal()

提交回复
热议问题