I'm having some problems with communicating between Threads in PyQt. I'm using signals to communicate between two threads, a Sender and a Listener. The sender sends messages, which are expected to be received by the listener. However, no messages are receieved. Can anyone suggest what might be going wrong? I'm sure it must be something simple, but I've been looking around for hours and not found anything. Thanks in advance!
from PyQt4 import QtCore,QtGui
import time
class Listener(QtCore.QThread):
def __init__(self):
super(Listener,self).__init__()
def run(self):
# just stay alive, waiting for messages
print 'Listener started'
while True:
print '...'
time.sleep(2)
def say_hello(self):
print ' --> Receiver: Hello World!'
class Sender(QtCore.QThread):
# a signal with no arguments
signal = QtCore.pyqtSignal()
def __init__(self):
super(Sender,self).__init__()
# create and start a listener
self.listener = Listener()
self.listener.start()
# connect up the signal
self.signal.connect(self.listener.say_hello)
# start this thread
self.start()
def run(self):
print 'Sender starting'
# send five signals
for i in range(5):
print 'Sender -->'
self.signal.emit()
time.sleep(2)
# the sender's work is done
print 'Sender finished'
I'm not sure if that is what you need, but it works fine...
from PyQt4 import QtCore,QtGui
import time
class Listener(QtCore.QThread):
def __init__(self):
super(Listener,self).__init__()
def run(self):
print('listener: started')
while True:
time.sleep(2)
def connect_slots(self, sender):
self.connect(sender, QtCore.SIGNAL('testsignal'), self.say_hello)
def say_hello(self):
print('listener: received signal')
class Sender(QtCore.QThread):
def __init__(self):
super(Sender,self).__init__()
def run(self):
for i in range(5):
print('sender: sending signal')
self.emit(QtCore.SIGNAL('testsignal'))
time.sleep(2)
print('sender: finished')
if __name__ == '__main__':
o_qapplication = QtGui.QApplication([])
my_listener = Listener()
my_sender = Sender()
my_listener.connect_slots(my_sender)
my_listener.start()
my_sender.start()
i_out = o_qapplication.exec_()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With