Skip to main content
 首页 » 编程设计

c++之为什么 QObject::findChildren 返回具有公共(public)基类的 child

2025年12月25日40pengyingh

我使用 QObject 作为复合模式的基类。

假设我有一个父类 File(在一个人为的示例中),我要向其中添加不同类型的子类,HeaderSection 和 PageSection。 File、HeaderSection 和 PageSection 都是 Section。 Section 的构造函数接受一个父对象,该对象传递给 QObject 的构造函数,设置父对象。

例如:

class Section : public QObject { 
 Q_OBJECT 
 
 // parent:child relationship gets set by QObject 
 Section(QString name, Section *parent=NULL) : QObject(parent) 
 { setObjectName(name);} 
 QString name(){return objectName();} 
}; 
 
class File: public Section { 
public: 
 // probably irrelevant to this example, but I am also populating these lists 
 QList<Section *> headers; 
 QList<Section *> pages; 
}; 
 
class Header : public Section { 
Header(QString name, File *file) : Section(name, file){} 
}; 
 
class Page: public Section { 
 Body(QString name, File *file) : Section(name, file){}  
}; 

定义中的构造语法可能不正确,抱歉,我习惯在外面做。无论如何,当我这样做时:
File *file = new file(); 
Header *headerA = new Header("Title", file); 
Header *headerB = new Header("Subtitle", file); 
Page *page1 = new Page("PageOne", file); 
Page *page2 = new Page("PageTwo", file); 
 
QList<Page*> pages = file->findChildren<Page*>(); 
 
for(int i=0; i < pages.size(); i++) 
  qDebug() << pages.at(i)->name(); 

我得到以下输出:

标题

字幕

第一页

第二页

我在这里想念什么?当然,如果 findChildren 寻找公共(public)基类,那么它只会返回 Widget 的每个子级(例如),我知道它在正常使用中并不常见。

另外,如果我遍历返回的 child 列表并使用 dynamic_cast<Page*>在每个返回的 child 上,我都会得到预期的两个 Page 项目。

请您参考如下方法:

答案就像@Mat 和@ratchet 怪胎告诉我的那样——我在每个子类中都需要 Q_OBJECT,而不仅仅是基类。