为什么 QObject ::findChildren 返回具有公共基类的子级?

mik*_*ike 5 c++ qt qobject

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

假设我有一个父类 File(在一个人为的示例中),我向其中添加不同类型的子类 HeaderSection 和 PageSection。File、HeaderSection 和 PageSection 都是节。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){} 
};
Run Code Online (Sandbox Code Playgroud)

定义中的构造语法可能不正确,抱歉,我习惯在外面这样做。无论如何,当我这样做时:

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();
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

标题

字幕

第一页

第二页

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

另外,如果我迭代返回的子项列表并dynamic_cast<Page*>在每个返回的子项上使用,我会得到预期的两个页面项。

mik*_*ike 2

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