QT

输出QT对象树

QT对象树机制

Posted by 雯饰太一 on May 28, 2023

输出QT对象树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void CountObjects(QObject* pRoot)
{
	//输出所有的子孩子
	QObject* pRootWidget = pRoot;
	QStack<QObject*> objStack;
	int iCnt = 0;
	objStack.push(pRootWidget);
	printf("****************Start Gount Object********************\n");
	while (!objStack.empty())
	{
		QObject* obj = objStack.pop();
		++iCnt;
		printf("%s, ", obj->objectName().toLocal8Bit().data());
		QObjectList objCList = obj->children();
		for each (QObject * var in objCList)
		{
			objStack.push(var);
		}
	}
	printf("\n**************Stop Gount Object: %d******************\n", iCnt);
}

AI Answer

要递归输出 Qt 对象树,你可以使用 QObject 的 children() 函数获取子对象列表,然后对每个子对象递归调用输出函数。以下是一个示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <QDebug>
#include <QObject>

void printObjectTree(QObject *object, int indent = 0)
{
    QString indentation(' ', indent * 4);
    qDebug() << indentation << object->objectName();

    // 获取子对象列表
    QList<QObject *> children = object->children();
    for (QObject *child : children) {
        // 递归调用输出函数
        printObjectTree(child, indent + 1);
    }
}

使用上述函数,你可以传入一个根对象,它将递归输出该对象及其所有子对象的名称。调用示例:

1
2
QObject *rootObject = ...; // 根对象
printObjectTree(rootObject);

输出的结果将会显示对象树的层次结构,每个对象前面会有相应的缩进。

请确保在调用 printObjectTree 函数时提供一个有效的根对象,并根据实际情况进行调整和修改。