我是pyqt的新手,我需要在与主UI不同的线程中创建套接字,起初我使用线程,但无论运行线程如何,它都会使我的主窗口崩溃。然后,我了解了QThread,它用于使用信号和插槽从线程更改QLabel。
但是目前这是我的代码的片段,Conn_BTN已连接到按钮。应用程序启动后,立即打印0,但不打印1-3和5,奇怪的是,甚至在0之前打印4。
def Conn_BTN(self): # Called by a QPushButton
print("0")
self.thread = QtCore.QThread(self)
print("1")
self.thread.started.connect(ServerThread.Socket_Conn)
print("2")
self.thread.start()
print("3")
@QtCore.pyqtSlot(int)
def on_sig_conn_stat(self, stat):
if(stat == 1):
MainWindow.statusBar.setMessage("Connected") # Changes the status from disconnected to connected
elif(stat == 0):
MainWindow.statusBar.setMessage("Disconnected")
class ServerThread(QtCore.QObject):
sig_conn_stat = QtCore.pyqtSignal(int)
print("4")
def __init__(self, id: int):
super().__init__()
self.__id = id
@QtCore.pyqtSlot()
def Socket_Conn(self):
print("5")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
s.bind(("0.0.0.0", 12345))
s.listen(5)
while (i = True):
app.processEvents()
c, addr = s.accept()
print ('Got connection from', addr)
code_encoded = c.recv(1024)
code_decoded = code_encoded.decode('utf-8')
if (code_decoded == "Conn"):
Print("Connected")
self.sig_conn_stat.emit(1)
else:
print(code_decoded)
c.close()
s.close()
self.sig_conn_stat.emit(0)
需要帮助的两件事:
1)为什么我的应用程序在不打印1-3的情况下关闭,为什么不打印4,并且打印出来是正常的
2)我更改标签的实现是否正确?