Get a list of all QObjects created in a Application

前端 未结 1 2107
[愿得一人]
[愿得一人] 2021-02-20 15:15

To get a list of all the QWidgets created in an application we can simply call QApplication::allWidgets().

I\'ve read the documentation, and I haven\'t foun

相关标签:
1条回答
  • 2021-02-20 15:28

    To begin with it's important to understand the difference between the QObject and QWidget classes.

    class QObject

    QObject instances have a pointer to their parent which may or may not be a null pointer. It's quite legitimate to create a QObject instance without a parent so long as you understand that it is your responsibility for that instance's lifetime i.e. if you don't delete it you will leak memory.

    class QWidget

    Although it appears you can create a QWidget without a parent, you can't. When you create an instance of a QWidget "without a parent" (i.e. by supplying a null pointer or letting it default to a null pointer) it's parent effectively gets set to your application's QApplication1 instance.

    Is there a method to obtain such a list?

    No. The reason QApplication::allWidgets() works is due to the fact that all QWidget instances have a pointer to them which is stored in your single QApplication instance. There is no central store of QObject pointers and therefore no in-built way of retrieving them.

    One way around this is to ensure yourself that all QObjects instances (or instances of classes which inherit QObject) have a valid parent. Then you can use the QObject functions children(), findChild() and findChildren() to get pointers to these objects.

    These are powerful tools, and like anything powerful, use them with care! Make sure you understand C++ object life spans before you use these in production code.



    Notes:

    1. QApplication inherits from QCoreApplication which inherits from QObject. There are some restrictions placed on how QApplication is used by the Qt framework.
    0 讨论(0)
提交回复
热议问题