├── README.md └── main.py /README.md: -------------------------------------------------------------------------------- 1 | # PyQT5 Threading The Right Way 2 | 3 | ### History 4 | After researching PyQT5 threading while updating a simple app with [cleary](https://github.com/cleary), we found that most of the documentation regarding this topic is incorrect, including official documentation. 5 | 6 | We eventually stumbled across a few articles (listed below) that had correct methods and documentation as to how this works. 7 | 8 | **Reference:** 9 | * https://www.learnpyqt.com/courses/concurrent-execution/multithreading-pyqt-applications-qthreadpool/ 10 | * https://stackoverflow.com/questions/11426335/qthread-execution-freezes-my-gui 11 | * https://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/ ...which dead links to where they promise the real information is. [Here is the referenced blog post on archive.org](https://web.archive.org/web/20200128030120/https://www.qt.io/blog/2006/12/04/threading-without-the-headache) 12 | 13 | ### Example Code: 14 | 15 | Functional threading example: [main.py](https://github.com/Givo29/pyqt5-threading/blob/master/main.py) 16 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import time 3 | from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox 4 | from PyQt5.QtGui import QIcon 5 | from PyQt5.QtCore import QThread, pyqtSignal, QThreadPool, pyqtSlot, QRunnable, QObject 6 | 7 | 8 | class Signals(QObject): 9 | return_signal = pyqtSignal(str) 10 | 11 | 12 | class Thread(QRunnable): 13 | signal = pyqtSignal(str) 14 | 15 | def __init__(self): 16 | super(Thread, self).__init__() 17 | self.signal = Signals() 18 | 19 | @pyqtSlot() 20 | def run(self): 21 | time.sleep(5) 22 | result = "Some String" 23 | self.signal.return_signal.emit(result) 24 | 25 | 26 | class App(QWidget): 27 | def __init__(self): 28 | super().__init__() 29 | self.title='Hello, world!' 30 | self.left=2100 31 | self.top=500 32 | self.width=640 33 | self.height=480 34 | self.threadpool = QThreadPool() 35 | self.initUI() 36 | 37 | def initUI(self): 38 | self.setWindowTitle(self.title) 39 | self.setGeometry(self.left,self.top,self.width,self.height) 40 | checkbox = QCheckBox('Check Box', self) 41 | checkbox.stateChanged.connect(self.clickCheckbox) 42 | self.show() 43 | 44 | def clickCheckbox(self): 45 | thread = Thread() 46 | thread.signal.return_signal.connect(self.function_thread) 47 | self.threadpool.start(thread) 48 | 49 | def function_thread(self, signal): 50 | print(signal) 51 | 52 | 53 | if __name__=='__main__': 54 | app=QApplication(sys.argv) 55 | ex=App() 56 | sys.exit(app.exec_()) --------------------------------------------------------------------------------