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



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

假设我有一个父类文件(在人为的示例中),我正在向其添加不同类型的子类,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){} 
};

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

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();

我得到以下输出:

标题

字幕

第一页

第二页

我在这里错过了什么?当然,如果findKids寻找公共基类,那么它只会返回小部件的每个子级(例如),我知道它在正常使用中不会。

此外,如果我遍历返回的子项列表并对每个返回的子项使用 dynamic_cast<Page*>,则会得到预期的两个 Page 项目。

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

最新更新