Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do i need to create object of `QApplication` and what is the purpose of it in PyQt GUI programming?

Tags:

python

qt

pyqt5

def main():
    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QWidget()
    w.show()

    app.exec()

This is a very simple Python GUI program with PyQt5 framework. Actually I'm not familiar with Qt, also a newbie to GUI programming. As in above program, there is a object of QApplication has created as well as QWidget. In this case, app object doesn't contain the w object and i don't see any connection between two of them. So why it's necessary to create a object of QApplication and to execute it using that object? Thank you!

like image 435
Srinesh Avatar asked Dec 07 '15 02:12

Srinesh


1 Answers

You don't need to create QApplication, but it's a convenience class that does a lot of things for you.

I won't explain everything it can possibly do for you -- you'll find that in the manual -- but I can explain two of the things you're doing in your sample code.

app = QtWidgets.QApplication(sys.argv)

Here you're creating the QApplication, and passing in arguments to its constructor. Qt understands certain arguments that can be used when executing the application.

app.exec_()

Like you said, there doesn't appear to be any interaction between app and w. But there is a connection!

In order for Qt's GUI to function it needs an event loop in the main thread. The call to exec_() starts this event loop.

To quote the documentation for 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. The main event loop receives events from the window system and dispatches these to the application widgets.

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

Pretty much all desktop GUIs work this way to some extent, though not all of them have a nice Application object that sets up the event loop for you. If you're new to event driven programming you might want to read up on the concepts. This Wikipedia article isn't a bad place to start.

like image 60
MrEricSir Avatar answered Sep 29 '22 07:09

MrEricSir