How to print in PyQt5 GUI program while the main window is running?

Question:

Currently i am working on a GUI program in PyQt5. My program has several steps which run after each other. After finish each step i want to print for example Step1 finished and then Step2 finished and so on. Since the main window freezes the print does not work.
It would be very helpful if you give me some solutions.

Asked By: hamid

||

Answers:

A simple solution would be a thread based solution, where you set an event flag after finishing the task:

import threading


done_flag = threading.Event()

def print_status():
    while True:
        done_flag.wait()
        print("I'm done!")
        done_flag.clear()

Inside your function, you have to call .set_flag. This functions blocks until your function have finished (if you always call set_flag).

It’s by the way always good practice to use threads in GUI applications. This avoids freezing cause the main loop etc. cannot run.

By the way, instead of raw printing, I would suggest using logging which gives more useful information.

Answered By: bilalj
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.