How are QApplication () and QWidget () objects connected in PySide / PyQt?

How are QApplication () and QWidget () related?

This is an example of the code I copied, it creates a QApplication object and a QWidget object, but there is no connection between the two objects. I was expecting something like app.setWidget(did) to teach the PySide / PyQt controller about the widget to be created.

 # http://zetcode.com/gui/pysidetutorial/firstprograms/ # 1. PySide.QtGui is the class import sys from PySide import QtGui # 2. setup the application app = QtGui.QApplication(sys.argv) # 3. create the widget and setup wid = QtGui.QWidget() wid.resize(250, 150) wid.setWindowTitle('Simple') # 4. Show the widget wid.show() # 5. execute the app sys.exit(app.exec_()) 

What magic is behind this?

+7
python qt pyqt pyside
source share
1 answer

QApplication is a singleton, so it would be pretty easy: QWidget to do: QApplication.instance() and interact with the QApplication instance.

In fact, trying to instantiate QWidget before QApplication produces an error:

 >>> QtGui.QWidget() QWidget: Must construct a QApplication before a QPaintDevice 

Most likely this is what happens.


Edit: I downloaded qt sources and, in fact, in line src/gui/kernel/qwidget.cpp , line 328, there is:

 if (!qApp) { qFatal("QWidget: Must construct a QApplication before a QPaintDevice"); return; } 

Where qApp is a pointer to a QApplication instance (i.e., it is equivalent to calling QApplication.instance() ).

So at the end, QWidget interacts with QApplication with a global variable, although this is not necessary. They probably use qApp instead of QApplication.instance() to avoid unnecessary overhead that can occur when creating / destroying many QWidget s.

+8
source share

All Articles