我使用 QObject 作为复合模式的基类。
假设我有一个父类 File(在一个人为的示例中),我向其中添加不同类型的子类 HeaderSection 和 PageSection。 File、HeaderSection 和 PageSection 都是节。 Section 的构造函数采用一个父对象,该对象被传递到 QObject 的构造函数,设置父对象。
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){}
};
定义中的构造语法可能不正确,抱歉,我习惯在外面这样做。无论如何,当我这样做时:
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();
我得到以下输出:
Title
Subtitle
PageOne
PageTwo
我在这里缺少什么?当然,如果 findChildren 寻找公共基类,那么它只会返回 Widget 的每个子级(例如),我知道它在正常使用中不会。
另外,如果我迭代返回的子项列表并使用dynamic_cast<Page*>
在每个返回的孩子上,我得到了预期的两个页面项目。