0

The problem is that even though I put the function in a separate thread, the window still does not respond to actions until it is fully executed. What is the problem? Just ctrl+c, ctrl+v the code below, you will see what i mean. If you have any questions, feel free to ask

import sys
import asyncio

from asyncqt import QEventLoop, asyncSlot
from pytube import YouTube
import time

from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QPushButton,
    QVBoxLayout)


class MainWindow(QWidget):

    def __init__(self):
        super().__init__()

        self.setLayout(QVBoxLayout())

        self.lblStatus = QLabel('Idle', self)
        self.layout().addWidget(self.lblStatus)

        self.editUrl = QLineEdit('Hi!', self)
        self.layout().addWidget(self.editUrl)

        self.editResponse = QTextEdit('', self)
        self.layout().addWidget(self.editResponse)

        self.btnFetch = QPushButton('Fetch', self)
        self.btnFetch.clicked.connect(self.on_btnFetch_clicked)
        self.layout().addWidget(self.btnFetch)

    @asyncSlot()
    async def on_btnFetch_clicked(self):
        self.lblStatus.setText('downloading...')
        yt = YouTube('https://www.youtube.com/watch?v=zG4uYN3n8zs')
        yt.streams.filter(resolution='720p').first().download('C:/Users/Andrew/Desktop')
        self.lblStatus.setText('downloaded!')
        


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()

    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    with loop:
        sys.exit(loop.run_forever())
Andrew
  • 41
  • 6
  • If the only problem is with `sleep` function then this can be marked as duplicate [asyncio-sleep-vs-time-sleep-in-python](https://stackoverflow.com/questions/56729764/asyncio-sleep-vs-time-sleep-in-python) – mx0 Nov 06 '22 at 19:38
  • Edited my example a bit. Used time.sleep() as a rough example. – Andrew Nov 06 '22 at 19:43
  • This can be done much more simply (and reliably) with QThread. All that async stuff is just needless bloat. All you need to do is create a subclass of `QThread` and reimplement its `run()` method by adding the two lines of youtube code to it. Then create an instance in `MainWindow.__init__` , connect its `finished` signal to a slot that updates the label, and call `self.mythread.start()` in the button handler. That's about all there is to it (apart from calling `app.exec()`). – ekhumoro Nov 06 '22 at 20:44

1 Answers1

0

Function time.sleep(5) is blocking, and await asyncio.sleep(5) is non-blocking.

mx0
  • 6,445
  • 12
  • 49
  • 54