Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GUI freezing in python PySide6

Tags:

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?
like image 696
David_F Avatar asked Oct 28 '25 10:10

David_F


1 Answers

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.

like image 191
Alexander Avatar answered Oct 30 '25 01:10

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!