Python library for using asyncio in Qt-based applications
Low maintenance activity. Last release 15 months ago, commits in 1 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install qasyncqasync
Introduction
qasync allows coroutines to be used in PyQt/PySide applications by providing an implementation of the PEP 3156 event loop.
With qasync, you can use asyncio functionalities directly inside Qt app's event loop, in the main thread. Using async functions for Python tasks can be much easier and cleaner than using threading.Thread or QThread.
If you need some CPU-intensive tasks to be executed in parallel, qasync also got that covered, providing QEventLoop.run_in_executor which is functionally identical to that of asyncio. By default QThreadExecutor is used, but any class implementing the concurrent.futures.Executor interface will do the job.
Basic Example
import asyncio
import sys
from PySide6.QtWidgets import QVBoxLayout, QWidget
from qasync import QApplication, QEventLoop
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setLayout(QVBoxLayout())
self.lbl_status = QLabel("Idle", self)
self.layout().addWidget(self.lbl_status)
@asyncClose
async def closeEvent(self, event):
pass
@asyncSlot()
async def onMyEvent(self):
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
app_close_event = asyncio.Event()
app.aboutToQuit.connect(app_close_event.set)
main_window = MainWindow()
main_window.show()
# for 3.11 or older use qasync.run instead of asyncio.run
# qasync.run(app_close_event.wait())
asyncio.run(app_close_event.wait(), loop_factory=QEventLoop)