Last active
February 7, 2020 00:17
-
-
Save csparker247/4318756d61df7dd8594ac11c68797efc to your computer and use it in GitHub Desktop.
PySide2 Grandchild Threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import shiboken2 | |
from PySide2.QtCore import QObject, QThread, Signal, Qt | |
from PySide2.QtWidgets import QApplication, QPushButton | |
class Grandchild(QObject): | |
def __init__(self, parent=None): | |
super(Grandchild, self).__init__(parent) | |
print('Grandchild()') | |
def __del__(self): | |
print('~Grandchild()') | |
class Child(QObject): | |
_thread = None | |
_worker = None | |
def __init__(self, parent=None): | |
super(Child, self).__init__(parent) | |
print('Child()') | |
def __del__(self): | |
print('~Child()') | |
if shiboken2.isValid(self._thread): | |
self.stop_thread() | |
def start_thread(self): | |
print('Starting grandchild thread') | |
self._thread = QThread(self) | |
self._worker = Grandchild() | |
self._worker.moveToThread(self._thread) | |
self._thread.finished.connect(self._worker.deleteLater) | |
self._thread.start() | |
def stop_thread(self): | |
print('Stopping grandchild thread') | |
self._thread.quit() | |
self._thread.wait() | |
def toggle_thread(self): | |
if self._thread and self._thread.isRunning(): | |
self.stop_thread() | |
else: | |
self.start_thread() | |
class Parent(QPushButton): | |
_thread = None | |
_worker = None | |
stop_child = Signal() | |
def __init__(self, parent=None): | |
super(Parent, self).__init__(parent) | |
print('Parent()') | |
self.setText('Start Grandchild') | |
self._thread = QThread(self) | |
self._worker = Child() | |
self._worker.moveToThread(self._thread) | |
self._thread.finished.connect(self._worker.deleteLater) | |
self._thread.start() | |
self.clicked.connect(self.on_push) | |
self.clicked.connect(self._worker.toggle_thread) | |
self.stop_child.connect(self._worker.stop_thread, Qt.BlockingQueuedConnection) | |
def __del__(self): | |
print('~Parent()') | |
self.stop_child.emit() | |
if shiboken2.isValid(self._thread): | |
self._thread.quit() | |
self._thread.wait() | |
def on_push(self): | |
if self.text() == 'Start Grandchild': | |
self.setText('Stop Grandchild') | |
else: | |
self.setText('Start Grandchild') | |
def main(): | |
app = QApplication(sys.argv) | |
widget = Parent() | |
widget.show() | |
sys.exit(app.exec_()) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment