Skip to content
Dec 30 / kkrizka

Recursively Printing Out The Parent Tree Of a QObject

Here is a snipplet of code that I find myself using quite often. It takes a QObject pointer obj as an argument and recursively prints out the names and types of the children of obj.

void listChildren(QObject *obj,int level=0)
{
 
  QString tabs="";
  for(int i=0;i<level;i++)
    tabs+="t";
  qDebug() << tabs << obj;
 
  QObjectList children=obj->children();
  for(int i=0;i<children.size();i++)
    listChildren(children[i],level+1);
}

I use this quite often, because I am currently dealing with creating a dynamic UI that contains widget that change parents often, like switching toolbars form one QMainWindow to another. This tends to cause problems and the above snipplet helps me to debug them. I just copy-paste the function straight into the .cpp file and use it. When I am done, I just delete it.

Leave a comment