【发布时间】:2021-06-03 19:00:03
【问题描述】:
我正在使用 PyQt5 在 Python 中创建服务器-客户端 GUI 应用程序。每当新客户端连接到服务器时,我都需要在服务器端显示客户端详细信息。我正在为套接字使用单独的线程。每当我调用client_connect 函数在服务器端添加小部件时,由于未显示哪个小部件而出现错误。我认为由于 GUI 和套接字代码在不同的线程中,因此我得到了错误。
QObject::setParent: 无法设置父级,新父级在不同的线程中
QObject::installEventFilter():无法过滤不同线程中对象的事件。
QBasicTimer::start: QBasicTimer 只能用于以 QThread 启动的线程
QBasicTimer::start: QBasicTimer 只能用于以 QThread 启动的线程
QBasicTimer::start: QBasicTimer 只能用于以 QThread 启动的线程
QObject::startTimer:定时器只能用于以 QThread 启动的线程
QBasicTimer::start: QBasicTimer 只能用于以 QThread 启动的线程
主要功能
if __name__ == "__main__":
thread1 = threading.Thread(target = ui.server_socket)
thread1.start()
client_connect 函数 - 我为小部件创建了一个单独的文件,并将小部件插入到 tableWidget 中。如果我直接调用该函数,它可以工作,但如果我从套接字代码调用它,它会给我错误。
def client_connect(self,clientid):
self.clientCount = self.clientCount + 1
self.clientList.append(clientid)
self.clientDict[clientid] = QtWidgets.QWidget()
self.clientDict[clientid].ui = clients()
self.clientDict[clientid].ui.setupUi(self.clientDict[clientid])
self.clientDict[clientid].ui.label_clientid.setText(str(clientid))
self.tableWidget_client.setRowCount(self.clientCount)
self.tableWidget_client.setCellWidget(self.clientCount-1,0,self.clientDict[clientid])
套接字编程
def start_socket(self):
self.ssock.listen(20)
while True:
conn, c_addr = self.ssock.accept()
print(conn,c_addr)
thread2 = threading.Thread(target=self.handle_client, args=(conn,c_addr))
thread2.start()
def handle_client(self, conn, c_addr):
try:
self.c = conn.recv(1024).decode(self.FORMAT)
thread3 = threading.Thread(target = self.client_connect, args = (self.c_id,))
thread3.start()
except socket.error as e:
print(e)
【问题讨论】:
标签: python multithreading sockets pyqt5