Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all QObjects created in a Application

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 found anything like this to get a list of all QObjects. If an application creates stand-alone QObjects that are not QWidgets I have no such function to use.

Is there a method to obtain such a list?

like image 291
BetterWalk Avatar asked Feb 26 '10 10:02

BetterWalk


1 Answers

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.
like image 116
Samuel Harmer Avatar answered Dec 29 '22 05:12

Samuel Harmer