Skip to main content

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 TaskSignal(QObject):
"""
QRunnable์—์„œ ์‚ฌ์šฉํ•  ์‹œ๊ทธ๋„
"""
finished = Signal(bool)
class Task(QRunnable):
_taskSignal = TaskSignal()
finished = _taskSignal.finished
var = False
def run(self):
"""
์ž ์‹œ ์ค‘๋‹จํ•˜๋Š” ๊ฒฝ์šฐ QThread.msleep() ์‚ฌ์šฉ
"""
QThread.msleep(5000)
self.finished.emit(self.var)
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.setText("๋ฒ„ํŠผ 1")
self.pushButton.clicked.connect(self.startTask)
self.task = Task()
self.task.setAutoDelete(False)
self.task.finished.connect(self.taskFinished)
def startTask(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 taskFinished(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)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())

Reference#

Last updated on