Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions qasync/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,24 +78,28 @@
from PyQt5.QtCore import pyqtSlot as Slot

QApplication = QtWidgets.QApplication
AllEvents = QtCore.QEventLoop.ProcessEventsFlags(0x00)

elif QtModuleName == "PyQt6":
from PyQt6 import QtWidgets
from PyQt6.QtCore import pyqtSlot as Slot

QApplication = QtWidgets.QApplication
AllEvents = QtCore.QEventLoop.ProcessEventsFlag(0x00)

elif QtModuleName == "PySide2":
from PySide2 import QtWidgets
from PySide2.QtCore import Slot

QApplication = QtWidgets.QApplication
AllEvents = QtCore.QEventLoop.ProcessEventsFlags(0x00)

elif QtModuleName == "PySide6":
from PySide6 import QtWidgets
from PySide6.QtCore import Slot

QApplication = QtWidgets.QApplication
AllEvents = QtCore.QEventLoop.ProcessEventsFlags(0x00)

from ._common import with_logger # noqa

Expand Down Expand Up @@ -234,7 +238,7 @@ def __exit__(self, *args):

def _format_handle(handle: asyncio.Handle):
cb = getattr(handle, "_callback", None)
if isinstance(getattr(cb, '__self__', None), asyncio.tasks.Task):
if isinstance(getattr(cb, "__self__", None), asyncio.tasks.Task):
return repr(cb.__self__)
return str(handle)

Expand Down Expand Up @@ -292,7 +296,11 @@ def timerEvent(self, event): # noqa: N802
handle._run()
dt = time.time() - t0
if dt >= loop.slow_callback_duration:
self._logger.warning('Executing %s took %.3f seconds', _format_handle(handle), dt)
self._logger.warning(
"Executing %s took %.3f seconds",
_format_handle(handle),
dt,
)
finally:
loop._current_handle = None
else:
Expand Down Expand Up @@ -338,7 +346,7 @@ class _QEventLoop:
... await asyncio.sleep(.1)
>>>
>>> asyncio.run(xplusy(2, 2), loop_factory=lambda:QEventLoop(app))

If the event loop shall be used with an existing and already running QApplication
it must be specified in the constructor via already_running=True
In this case the user is responsible for loop cleanup with stop() and close()
Expand Down Expand Up @@ -420,7 +428,9 @@ def stop(*args):
self.run_forever()
finally:
future.remove_done_callback(stop)
self.__app.processEvents() # run loop one last time to process all the events
self.__app.eventDispatcher().processEvents(
AllEvents
) # run loop one last time to process all the events
if not future.done():
raise RuntimeError("Event loop stopped before Future completed.")

Expand Down
32 changes: 32 additions & 0 deletions tests/test_qeventloop.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import asyncio
import ctypes
import threading
import logging
import multiprocessing
import os
Expand Down Expand Up @@ -874,6 +875,37 @@ async def main():
assert not loop.is_running()


def test_qeventloop_in_qthread():
class CoroutineExecutorThread(qasync.QtCore.QThread):
def __init__(self, coro):
super().__init__()
self.coro = coro
self.loop = None

def run(self):
self.loop = qasync.QEventLoop(self)
asyncio.set_event_loop(self.loop)
asyncio.run(self.coro)

def join(self):
self.loop.stop()
self.loop.close()
self.wait()

event = threading.Event()

async def coro():
await asyncio.sleep(0.1)
event.set()

thread = CoroutineExecutorThread(coro())
thread.start()

assert event.wait(timeout=1), "Coroutine did not execute successfully"

thread.join() # Ensure thread cleanup


def teardown_module(module):
"""
Remove handlers from all loggers
Expand Down
Loading