I am trying to use youtube-dl module to download videos from youtube. I created a simple GUI to do a little job, I need when user clicks start button the thread will be called and download starts and sends data using emit method, when this data arrives to read function in Main class, the thread must stops after call stop function from GUI, I tried to make event loop in qthread using exec_() and stop thread with exit, and I tried too use terminate but the GUI freezes.
The code that I used is:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from youtube_dl import *
class Worker(QThread):
data = pyqtSignal(object)
def __init__(self):
super(Worker, self).__init__()
self.flag = True
def sendHook(self, data, status = {'status':'downloading'}):
self.data.emit(data)
def stop(self):
self.quit()
self.exit()
def run(self):
self.y = YoutubeDL({'progress_hooks':[self.sendHook]})
self.y.download(['https://www.youtube.com/watch?v=LKIXbNW-B5g'])
self.exec_()
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
layout = QVBoxLayout()
self.l = QLabel("Hello")
b = QPushButton("Start!")
b.pressed.connect(self.connectthread)
layout.addWidget(self.l)
layout.addWidget(b)
w = QWidget()
w.setLayout(layout)
self.setCentralWidget(w)
self.show()
def read(self, data):
self.thread.stop()
def connectthread(self):
self.thread = Worker()
self.thread.data.connect(self.read)
self.thread.start()
app = QApplication([])
window = MainWindow()
app.exec_()