QMessage in a function thread?

Question:

I want to do a popup when the function in a thread finish but when it run the popup the program crash. I tried doing a thread in the main function thread but crash the app.

I put a large and slow funtion in a thread to not crash the GUI but I want when this slow function finish, run a popup with QMessageBox, my sollution work but when I press the ‘Ok’ button in the popup crash the program, but I dont want that, so I tried to make a thread from the main thread but do the same, only crash the program.

I want something like this:

def popup():
    msg = QMessageBox()
    msg.setWindowTitle("Alert")
    ...
    a = msg.exec_()

def slow_func():
    time.sleep(10) # exemple of slow
    popup() # when I press 'Ok' crash so I tried...

# I tried...

def slow_func():
    time.sleep(10) # exemple of slow
    threading.Thread(target=popup).start() # still crashing

threading.Thread(target=slow_func).start()

I don’t know how to do it, I tried a thread in a thread but still crashing when I press ‘Ok’ button. The popup works but crash the app when I press ‘Ok’

I’m in Windows 11 using python 3.10 and PyQt 5.15

Asked By: Miguel de Haroce

||

Answers:

You must not use any GUI functions outside of the main thread. So you can not call popup() from your calculation thread and you can’t create a new thread in your calculation thread and have that call it. You must make the main thread call it.

For possible solutions see How to properly execute GUI operations in Qt main thread?

In short: Use the signal-slot-mechanism or QMetaObject::invokeMethod()

Answered By: SebDieBln