gpt4 book ai didi

python - PyQt 中的线程和信号问题

转载 作者:太空狗 更新时间:2023-10-29 22:23:55 25 4
gpt4 key购买 nike

我在 PyQt 中的线程之间进行通信时遇到了一些问题。我正在使用信号在两个线程(一个发送者和一个监听器)之间进行通信。发件人发送消息,这些消息预计会被收听者接收。但是,没有收到任何消息。谁能建议可能出了什么问题?我敢肯定它一定很简单,但我已经四处寻找了几个小时,但没有找到任何东西。提前致谢!

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'

最佳答案

我不确定这是否是您需要的,但它工作正常...

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_()

关于python - PyQt 中的线程和信号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4323678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com