PySide2 QRunnable and QThreadPool

Examples

import sys
from PySide2.QtWidgets import QMainWindow, QApplication
from PySide2.QtCore import (
QObject,
QThread,
QRunnable,
QThreadPool,
Slot,
Signal,
)
from ui_mainwindow import Ui_MainWindow
class Task_signal(QObject):
"""
QRunnable์—์„œ ์‚ฌ์šฉํ•  ์‹œ๊ทธ๋„
"""
finished = Signal(bool)
class Task(QRunnable):
_sig = Task_signal()
finished = _sig.finished
var = False
def run(self):
"""
์ž ์‹œ ์ค‘๋‹จํ•˜๋Š” ๊ฒฝ์šฐ QThread.msleep() ์‚ฌ์šฉ
"""
QThread.msleep(5000)
self.finished.emit(self.var)
class Main_window(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.task_start)
self.task = Task()
self.task.setAutoDelete(False)
self.task.finished.connect(self.task_finished)
def task_start(self):
if self.task.var:
self.task.var = False
else:
self.task.var = True
"""
task ์‹คํ–‰
"""
QThreadPool.globalInstance().start(self.task)
"""
๋ฒ„ํŠผ ๋น„ํ™œ์„ฑํ™”
"""
self.pushButton.setEnabled(False)
@Slot(bool)
def task_finished(self, is_success):
if is_success:
self.textBrowser.append("success")
else:
self.textBrowser.append("fail")
self.pushButton.setEnabled(True)
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = Main_window()
main_window.show()
sys.exit(app.exec_())

Reference

Last updated on