David_F
David_F

Reputation: 43

GUI freezing in python PySide6

I am developing a software as part of my work, as soon as I make a call to the API to fetch data the GUI freezes, at first I understood the problem and transferred the functions to threads, the problem is that once I used the join() function the app froze again. What I would like is to wait at the same point in the function until the threads end and continue from the same point in the function, is there any way to do this in Python?

threads = []
def call_api(self, query, index, return_dict):
    thread = threading.Thread( target=self.get_data, args=(query, index, return_dict)) 
    self.threads.append(thread)
    thread.start()

def get_all_tickets(self, platform):
    if platform == 'All':

    self.call_api(query1, 0, return_dict)
    self.call_api(query2, 1, return_dict)

    for thread in self.threads:
         thread.join()
     # The app freezes here
     # Is there a way to wait at this point asynchronously until the processes are complete 
    and continue from that point without the GUI freezing?

Upvotes: 4

Views: 1018

Answers (1)

Alexander
Alexander

Reputation: 17301

One possible option would be to use QThreads finished signal it emits that you can connect to with a slot that contains the remaining logic from your get_all_tickets method.

threads = []
def call_api(self, query, index, return_dict):
    thread = QThread() 
    worker = Worker(query, index, return_dict)
    worker.moveToThread(thread)
    thread.started.connect(worker.run)
    worker.finished.connect(thread.terminate)
    thread.finished.connect(self.continue_getting_all_tickets)    
    self.threads.append(thread)
    thread.start()

def get_all_tickets(self, platform):
    if platform == 'All':
        self.call_api(query1, 0, return_dict)
        self.call_api(query2, 1, return_dict)

def continue_getting_all_tickets(self):
    # this will be called once for each and every thread created
    # if you only want it to run once all the threads have completed 
    # you could do something like this:
    if all([thread.isFinished() for thread in self.threads]):
        # ... do something
    

The worker class could look something like this.

class Worker(QObject):
    finished = Signal()
    def __init__(self, query, index, return_dict):
        super().__init__()
        self.query = query
        self.index = index
        self.return_dict = return_dict

    def run(self):
        # this is where you would put `get_data` code
        # once it is finished it should emit the finished signal
        self.finished.emit()      

Hopefully this will help you find the right direction.

Upvotes: 3

Related Questions