Why do I need to create a `QApplication` object and what is its purpose in programming the PyQt GUI?

def main(): app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QWidget() w.show() app.exec() 

This is a very simple Python GUI program with the PyQt5 framework. I'm actually not familiar with Qt, new to GUI programming. As in the previous program, a QApplication object is created, as well as a QWidget. In this case, the app object does not contain the w object, and I do not see any connection between the two of them. So, why do you need to create a QApplication object and execute it using this object? Thanks!

+6
source share
1 answer

You do not need to create QApplication, but it is a convenience class that does a lot for you.

I will not explain everything that he can do for you - you will find it in the manual - but I can explain two things that you do in your code example.

 app = QtWidgets.QApplication(sys.argv) 

Here you create a QApplication and pass arguments to its constructor. Qt understands certain arguments that can be used when running an application.

 app.exec_() 

As you said, there is no interaction between app and w . But there is a connection!

In order for the Qt GUI to function, it needs an event loop in the main thread. A call to exec_() triggers this event loop.

To cite the documentation for QApplication :: exec () :

It enters the main event loop and waits for exit () to be called, then returns the value that was set for exit () (which is 0 if exit () is called via quit ()).

This function must be called to start event processing. the main event loop receives events from the window system and sends it for application widgets.

So, as soon as you call exec_() , the control leaves your main() function and starts responding to user interface events until you tell it to exit.

Almost all desktop graphical interfaces work to some extent, although not all of them have a good application object that sets up an event loop for you. If you are new to event-based programming, you can familiarize yourself with the concepts. This Wikipedia article is not a bad place to start.

+7
source

All Articles