Why is QObject ::findChildren returning children with a common base class?

ぃ、小莉子 提交于 2019-12-10 20:21:35

问题


I am using QObject as a base class for a composite pattern.

Say I have a parent class File (in a contrived example) to which I am adding children of different types, HeaderSection and PageSection. File, HeaderSection and PageSection are all Sections. The constructor for Section takes a parent object which is passed through to QObject's constructor, setting the parent.

e.g:

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){} 
};

Syntax for construction in the definition may be incorrect, apologies, I'm used to doing it outside. Anyway, when I do this:

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

I get the following output:

Title

Subtitle

PageOne

PageTwo

What am I missing here? Surely if findChildren looked for common base classes then it would only ever return every single child of a Widget (for example), which I know it doesn't in normal use.

Also, if I iterate over the list of children returned and use dynamic_cast<Page*> on each returned child, I get the expected two Page items.


回答1:


The answer is as @Mat and @ratchet freak tell me - I needed Q_OBJECT in every subclass, not just the base class.



来源:https://stackoverflow.com/questions/35869441/why-is-qobject-findchildren-returning-children-with-a-common-base-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!