What is the intended way of blocking synchronous slots until some async. code is done?
See original GitHub issueSometimes it is required to wait for result of asynchronous operation in synchronous Qt slot, is there any proper way to do it?
For example I have QMainWindow subclass that has QWebEngineView as one of it’s child, QWebEngineView runs some JavaScript client code, and my application communicates with it asynchronously using WebSockets.
Now I want to request from QWebEngineView some data to store on application exit: in overridden QMainWindow::closeEvent()
.
I can’t create async. task and let closeEvent()
to finish, since the main window will destroy QWebEngineView on close, and most probably I won’t get results in time.
I can’t use BaseEventLoop.run_until_complete()
with my async. call, since event loop is already running and is not reentrant.
I can’t create second thread, start second event loop there, call async. method in the second event loop, and in closeEvent()
wait when the thread will finish, since my web socket is already managed by event loop in the main thread.
My current solution is to postpone the main window closing by ignoring first close event, start async. task, and call QMainWindow::close()
second time manually from async. task when work is done.
This solution works in closeEvent()
, since it’s possible to postpone closing, but will not in most of other synchronous slots.
Issue Analytics
- State:
- Created 8 years ago
- Comments:12 (5 by maintainers)
Top GitHub Comments
Maybe more related to #11, but I’ve found this syntax (
asyncSlot()
) quite useful:Cancelling the task?
@gmarull I really like this solution! Thanks.
Can you think of a way of cancelling the task created by
asyncio.ensure_future
?The only way I could think of doing it is below.
When the cancel button is pressed I search all running tasks and match the task’s coroutine’s
__qualname__
attribute to that ofasync def
method name on the object. It’s pretty gross.(In
asyncSlot
I also added a done callback on the task so that any exceptions can be caught).