0

I want to update the popup progress bar.

I refer to How to properly quit a QThread in PyQt5 when using moveToThread, Background thread with QThread in PyQt

In MainWindow, When I clicked a button, the program does some work and SubWindow(progressbar) will show. And I think, thread starts, the thread sends a signal to SubWindow(progressbar). But the program is dead right after SubWindow show. I use Jupiter notebook.

Here is my code.

class MainWindow(QMainWindow, FORM):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.button_num.clicked.connect(self.save_num)

    def save_num(self):
        s = SubWindow(5)
        save_thread = QThread()
        save_obj = save_object()
        save_obj.moveToThread(save_thread)
        save_obj.progress_signal.connect(s.progress_value)
        save_obj.finished.connect(save_thread.quit)
        save_thread.started.connect(save_obj.save_num)
        save_thread.start()


class SubWindow(QWidget):
    
    def __init__(self, val):
        super().__init__()
        self.progress = QProgressBar()
        self.progress.setMinimum(0)
        self.progress.setMaximum(val)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.progress)
        self.setLayout(self.layout)
        self.show()
        
    @pyqtSlot(int)
    def progress_value(self, val):
        self.progress.setValue(val)


class save_object(QObject):
    
    progress_signal = pyqtSignal(int)
    finished = pyqtSignal()
    
    def save_num(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print(count)
            count += 1
            self.progress_signal.emit(count)
        self.finished.emit()
  1. Is it the right way?
  2. What is the problem?
FireWood
  • 23
  • 5
  • What do you mean by "But the program is dead when SubWindow show"? – musicamante Jul 10 '21 at 14:41
  • @musicamante Oops, I mean 'But the program is dead right after SubWindow show.' My mistake – FireWood Jul 10 '21 at 14:44
  • Does this answer your question? [QThread: Destroyed while thread is still running in Python](https://stackoverflow.com/questions/34851261/qthread-destroyed-while-thread-is-still-running-in-python) – musicamante Jul 10 '21 at 16:46
  • You're not creating a static reference to none of the three objects (the dialog, the QThread and the save_object), so they get destroyed (see: garbage collected) as soon as that function returns. Just make them instance attribute: `self.s = SubWindow(5)`, etc – musicamante Jul 10 '21 at 16:47
  • @musicamante Wow, you're right. Thank you very much!! – FireWood Jul 11 '21 at 09:45

0 Answers0