Answer the question
In order to leave comments, you need to log in
How to stop asyncio loop in QThread?
Good afternoon, I'm writing a utility, I ran into a problem: when closing, everything just simply freezes ...
As I understand it, the event loop in QThread is not closed. So the question is:
Tell me how to close the event loop correctly.
from PyQt5.QtCore import QThread, QObject, pyqtSlot
from PyQt5.QtWidgets import QMainWindow, QApplication
import asyncio
import websockets
class ExampleWorker(QObject):
def __init__(self):
super().__init__()
@pyqtSlot()
def start(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.loop.run_until_complete(websockets.serve(self.echo, 'localhost', 8765))
self.loop.run_forever()
async def echo(self, websocket, path):
async for message in websocket:
await websocket.send(message)
class Example(QMainWindow):
def __init__(self):
self.app = QApplication([])
super().__init__()
self.obj = ExampleWorker()
self.thread = QThread()
self.obj.moveToThread(self.thread)
self.thread.started.connect(self.obj.start)
self.thread.start()
self.show()
self.app.exec_()
def closeEvent(self, event):
self.thread.quit()
self.thread.wait()
Example()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question