pyqt qthread似乎在应该时不会发出信号。我想用PYQT5构建代码的一部分,该代码可以与服务器通信。我希望它在单独的线程中,因为我主要在图像上操作,因此可能需要一些时间发送它。我希望能够发送它,当它从服务器接收响应时,它应该发出一个信号,允许发送下一个数据。
这是将代码减少到最低。
导入系统 导入时间
from PyQt5.Qt import QThread, QWidget, QApplication
from PyQt5.QtCore import pyqtSignal
def ask_server():
return b'some_message_received'
def send_to_server(data):
pass
class QTClient(QThread):
result_signal = pyqtSignal(bytes)
def __init__(self, *args, **kwargs):
QThread.__init__(self)
self._data = None
self._result = ' '
def set_data(self, data):
self._data = data
def set_result(self, result):
self._result = result
def receive_data(self):
result = ask_server()
print('receiving_data{}'.format(result))
self.result_signal.emit(result)
self._result = result
def send_data(self, data):
send_to_server(data)
self._data = None
def run(self):
broadcast = True
while broadcast:
if self._data is not None:
self.send_data(self._data)
self.receive_data()
if self._result is None:
self.receive_data()
class QtClientManager(QWidget):
data = pyqtSignal(bytes)
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.slam_client = QTClient()
self.data[bytes].connect(self.slam_client.set_data)
self._result = ''
self.slam_client.result_signal[bytes].connect(self.get_result)
self.thread_slam = QThread()
self.slam_client.moveToThread(self.thread_slam)
self.slam_client.start()
def add_image(self, data):
print('adding data {}'.format(data))
self.data.emit(data)
def get_result(self, result):
print('getting result data {}'.format(result))
self._result = result
def loop1():
for i in range(2):
qqq.add_image(b'sssss')
while qqq._result != b'some_message_received':
time.sleep(1)
def loop2():
for i in range(2):
qqq.add_image(b'sssss')
#while qqq._result != b'some_message_received':
time.sleep(1)
if __name__ == "__main__":
app = QApplication([])
qqq = QtClientManager()
loop1()
sys.exit(app.exec_())
使用loop1()的代码输出:
adding data b'sssss'
receiving_datab'some_message_received'
(它被卡住了)
loop2()代码的输出:
adding data b'sssss'
receiving_datab'some_message_received'
adding data b'sssss'
receiving_datab'some_message_received'
getting result data b'some_message_received'
getting result data b'some_message_received'
在我看来,从 receive_data()
中发出的信号以某种方式卡住,而不是将数据发送到qtclientmanager类。如何这样做,以免阻止?
我在代码中也有类似的问题,然后发现这是由于连接函数多次注册,这又导致了对emit函数的多次调用