Use Qt Pyside2 with asyncio await syntax?

Question:

How to await this function (src ) in the main loop of pyside2:

async def do_request(value): #asyncqt maybe possible
    #print("do request")
    await asyncio.sleep(value)
    #print("request finished")
    return value

async def eventFilter(self, source, event): #impossible, needs pyside2 rewrite
     ... 

I am very reluctant to use any nonoffical stuff, so pyside2: i looked into examples of pyside2 having Qthreads examples, but no asyncio await. My lib uses asyncio so how to await in pyside2?

This is a serious issue: The https://github.com/harvimt/quamash/issues/104 does not support pyside2 and https://github.com/gmarull/asyncqt is not maintained. What is the solution?
Please how to integrate such simple call. i fear breaks/bugs on nonmaintained repos

Asked By: droid192

||

Answers:

PyQt is very popular. Though some may not want it because of licensing issues. Whether you choose PyQt or PySide, QTimer has some very nice functionality. In particular, you can use the singleShot() method to run code at a specific delay.

from PySide2.QtCore import QTimer

def myfunc():
    # do your stuff here
    pass

def do_request(self, value):
    # call static function singleShot
    QTimer.singleShot( delay_msec, myfunc)

you can also start() a QTimer to run a task at a regular interval.

Answered By: bfris

after watching https://www.youtube.com/watch?v=ol5IuJyw-Tg using built in qthread qrunnable qthread to not block main gui thread is way to go.

for examples see https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/corelib and browse the source (its for pyside2)

Answered By: droid192

There are external libraries (asyncqt, qasync) to make Qt and asyncio play nicely, but such libraries seem to have poor support. The official PySide6 seems to have proper support with a module called QtAsyncio which is probably best (example here).

BUT this was affecting me in PySide2, and I found it best to simply run my asyncio event loop in a separate threading.Thread, with the Qt exec_ event loop in the main thread, and communicating between them with Qt Slots/Signals. That way could I fetch things in the background with the async/await syntax and keep the window running smoothly.

Hope it helps!

Answered By: J. Doe