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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With