Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current QApplication?

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.

like image 485
thor Avatar asked Nov 20 '18 06:11

thor


People also ask

What is QApplication in Qt?

The QApplication class manages the GUI application's control flow and main settings. QApplication contains the main event loop, where all events from the window system and other sources are processed and dispatched. It also handles the application's initialization, finalization, and provides session management.

What is the purpose of the exec () method of the QApplication class?

[static] int QApplication::exec() Enters the main event loop and waits until exit() is called, then returns the value that was set to exit() (which is 0 if exit() is called via quit()). It is necessary to call this function to start event handling.

What is the purpose of app QApplication SYS argv?

Passing sys. argv to QApplication at startup allows you to customize the behavior of Qt from the command-line. If you don't want to pass command-line arguments to Qt you can skip passing sys.

What is a signal in PyQt?

Signals are notifications emitted by widgets when something happens. That something can be any number of things, from pressing a button, to the text of an input box changing, to the text of the window changing. Many signals are initiated by user action, but this is not a rule.


1 Answers

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([])
like image 99
eyllanesc Avatar answered Sep 24 '22 03:09

eyllanesc