QObject Subclass Template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
# SImilar to the above article but with a QThread subclass

import sys

from PySide6.QtCore import QThread, Slot, Signal, Qt
from PySide6.QtWidgets import (QApplication, QPushButton,
    QLabel, QWidget, QVBoxLayout)


class WorkerThread(QThread):
    
    progress = Signal()
    error = Signal(str)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        print('Init in', QThread.currentThread().objectName())
        
    def run(self):
        print('Running in', QThread.currentThread().objectName())
        self.progress.emit()
        print('Hello World')


class Window(QWidget):
    
    def __init__(self):

        super().__init__()
        
        QThread.currentThread().setObjectName('Main thread')
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        button = QPushButton('Start background thread')
        button.clicked.connect(self.on_button_clicked)
        
        self.label = QLabel()
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        layout.addWidget(button)
        layout.addWidget(self.label)
    
    @Slot()
    def on_button_clicked(self):
        
        self.worker_thread = WorkerThread()
        self.worker_thread.setObjectName('Worker thread')
        
        self.worker_thread.finished.connect(self.on_finished)
        
        self.worker_thread.error.connect(self.on_error)
        self.worker_thread.started.connect(self.on_started)
        self.worker_thread.progress.connect(self.on_progress)
        
        self.worker_thread.start()
    
    @Slot()
    def on_started(self):
        print('thread started')
        
    @Slot()
    def on_progress(self):
        print('working')
    
    @Slot()
    def on_finished(self):
        self.label.setText('Worker finished')
    
    @Slot()
    def on_error(self, message):
        print(message)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    main_window = Window()
    main_window.show()

    sys.exit(app.exec())