我使用QObject作为复合模式的基类。
假设我有一个父类File(在一个人为的例子中),我将添加不同类型的子项,HeaderSection和PageSection。 File,HeaderSection和PageSection都是Sections。 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();
我得到以下输出:
标题
字幕
PAGEONE
PageTwo
我在这里缺少什么?当然,如果findChildren寻找公共基类,那么它只会返回Widget的每个子节点(例如),我知道它在正常使用中并不存在。
另外,如果我遍历返回的子项列表并在每个返回的子项上使用dynamic_cast<Page*>
,我会得到预期的两个Page项。
答案 0 :(得分:0)
答案是@Mat和@ratchet怪告诉我 - 我需要每个子类中的Q_OBJECT,而不仅仅是基类。