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

后端 未结 1 970
悲&欢浪女
悲&欢浪女 2020-12-07 01:29

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 betwee

相关标签:
1条回答
  • 2020-12-07 01:54

    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.

    0 讨论(0)
提交回复
热议问题