Search code examples
pythonpyqtpysideevent-loop

Does an event loop keep running the program's code in PyQt/PySide?


I know that when creating a QApplication, an evet loop is created. Does this mean that application will keep running the codes for ever untill it's terminated? I was trying to call a slot in my Main class constructor and i wondered if that slot would keep executing since there is an event loop thus the Main class would be instantialized for ever. How am i wrong? Why is the consructor method run only once?


Solution

  • The event loop is just an infinite loop that pulls events off of a queue and processes them.

    def exec_():
        while True:
            event = event_queue.get()
            process_event(event)
    

    The event loop is run when you call the "exec_()" method. When you click or interact with the GUI you are putting an event on the event queue. Qt internally processes that event.

    You will also notice that a long running button click will halt the GUI. Everything is running synchronously. When a button is clicked that event is being processed. No other events are processed while that event is running.

    import time
    from PySide2 import QtWidgets
    
    app = QtWidgets.QApplication([])
    
    def halt_10_sec():
        time.sleep(10)  # Stay here for 10 seconds
    
    btn = QtWidgets.QPushButton('Halt')
    btn.clicked.connect(halt_10_sec)
    btn.show()
    
    app.exec_()  # Run forever until app.quit()
    
    # You will not get here until all windows are closed and the application is exiting.
    print('Here')
    

    Once you click the button you will not be able to resize the window, move the window, highlight the button on hover, or any other events while the button event is running.

    A slot is just a function. You should be able to call a slot in the constructor.