How to get the current QApplication?

12.1k Views Asked by At

I am trying to get a reference to the current QApplication object with pyQt5, but couldn't find the function. My search about "pyQt get current QApplication" shows results about how to create an QApplication. So my question is:

Is there a global QApplication object, and if so how can get a reference to an existing (the current) application.

The reason I ask, is that I want to test if a debugging code is running within a Qt GUI application. Then, I'd like to bring up a QMessagebox to show error messages if the function is used in a Qt application; or print out a message to stdout otherwise.

1

There are 1 best solutions below

0
On BEST ANSWER

there should only be one QApplication, and if we want to obtain the existing one, you must use instance(), a common approach is to use the following technique:

app = QtWidgets.QApplication.instance()
if app is None:
    # if it does not exist then a QApplication is created
    app = QtWidgets.QApplication([])