简体   繁体   English

如何在不同模块之间使用信号

[英]How to use signal between different modules

I know how to use signal in a module or class like this: 我知道如何在这样的模块或类中使用信号:

 class A (QObject):
    def __init__(self):
        QObject.__init__(self)

    def afunc (self, i):
        self.emit(SIGNAL("doSomePrinting(int)"), i)    

    def bfunc(self, i):
        print "Hello World!", i
        sys.exit()

if __name__=="__main__":
    app=QCoreApplication(sys.argv)
    a=A()
    QObject.connect(a,SIGNAL("doSomePrinting(int)"),a.bfunc)
    a.afunc(10)    
    sys.exit(app.exec_())

But I don't know how to use signal between different modules, for example: a.py and b.py .I define and bound signal in a class of a.py ,and I want emit the signal to call the bound slot which define in a.py in b.py. 但是我不知道如何在不同模块之间使用信号,例如:a.py和b.py。我在a.py类中定义并绑定了信号,我想发出信号以调用绑定的插槽,在b.py中的a.py中定义。

I use this way: 我用这种方式:

self.logsignal.connect(self.handle) signalMange.signal = self.logsignal self.logsignal.connect(self.handle)signalMange.signal = self.logsignal

I use a class to store the instance in a.py and I call it in b.py like this: 我使用一个类将实例存储在a.py中,并在b.py中将其命名为:

signalMange.signal.emit('start write project...') signalMange.signal.emit('开始写项目...')

What about my way? 那我呢 Are there better ways? 有更好的方法吗?

"a.py" “ a.py”
The class A has a signal called my_signal and we have defined a method_for_signal in our class. 类A有一个名为my_signal的信号,我们在类中定义了method_for_signal。

from PyQt4 import QtCore, QtGui

class A(QObject):
    my_signal = QtCore.pyqtSignal(str)

    def __init__():
        super(A, self).__init__()
        self.name = "ABCDEFGHIJKLM"

    def method_for_signal(self):    
        self.my_signal.emit(self.name)

"b.py" “ b.py”

Here the class A is imported in class B, where we want to our signal. 在这里,A类是在B类中导入的,我们要在其中发出信号。

from a import A
class B(QObject):

    def __init__():
        super(B, self).__init__()

    @staticmethod
    def update(name):
        print str(name)

    def signal_connect(self):
        self.obj = A()
        self.obj.my_signal.connect(B.update)

The signal_connect method of class B when invoked will make our signal give the desired output. B类的signal_connect方法在被调用时将使我们的信号提供所需的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM