I have a really particular issue with a Python program I'm writing where I need a process to concurrently be running while a long-running function is carried out on the main thread
For clarity/example, let's say I have 2 necessary functions:
- A function that increments a progress bar by 1 every second
- A function that carries out a very long (30+ seconds) analysis and must be ran on the main thread (no exceptions, I've confirmed there is no workaround for this rule)
With that, I need these to concurrently run, so that the progress bar is incrementing while the analysis is being ran. So naturally, I make a thread to increment the progressbar and try to call that before calling the analysis function like so:
class ProgressThread(QThread):
_signal = pyqtSignal(int)
def __init__(self):
super(Thread, self).__init__()
def run(self):
progress = True
pct = 0
while progress: #while thread is running
time.sleep(1) #wait 1 sec
pct += 1
self._signal.emit(pct) #emit signal to increment progressbar
class Window(QMainWindow):
def __init__(self):
self.progressbar = QProgressBar() #init progressbar
def main(self):
self.thread = ProgressThread()
self.thread._signal.connect(self.increment_progressbar)
self.thread.start() #start progressbar incrementer thread
result = long_analysis_function() #start analysis function
def increment_progressbar(self, percent): #helper function to increment progressbar
self.progressbar.setValue(percent)
However, this code blocks the ProgressThread until the long_analysis_function()
finishes, so the progress bar just stays frozen during analysis and jumps to x% once the analysis function finishes.
I believe this could be solved by moving the analysis function to it's own thread, as the progress bar and analysis run in this scenario as epected, but then the analysis thread throws an error for not being in 'main thread', so I am literally unable to do that.
With that, how can I make it so my progress bar increment or thread properly while the analysis function runs concurrently in the main thread?