Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

How QApplication() and QWidget() are connected?

This is an example code that I copied, it creates QApplication object and QWidget object, but there is no link between the two objects. I expected something like app.setWidget(did) to teach PySide/PyQt controller about the widget that was 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's the magic behind this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

In fact trying to instantiate QWidget before the QApplication leads to an error:

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

Which probably means this is what happens.


Edit: I've downloaded the qt sources and in fact, in 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 the QApplication instance(i.e. it is equivalent to calling QApplication.instance()).

So, in the end, the QWidget interacts with the QApplication via a global variable, even though it isn't necessary. They probably use qApp instead of QApplication.instance() to avoid unnecessary overhead that might happen when creating/destroying many QWidgets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...