为什么 QObject ::findChildren 返回具有公共基类的子项
Why is QObject ::findChildren returning children with a common base class?
我正在使用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,而不仅仅是基类。
相关文章:
- std::具有相同基类的类的变体
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 基类中的函数名称解析
- C++初始化基类
- 如何通过派生类函数更改基类中的向量
- 如何定义一个纯抽象基类
- 如何使用基类指针引用派生类成员
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 公开最直接的基类模板名称
- 当基类是依赖类型时,这是一个缺陷吗
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 模板基类中的静态变量
- QObject基类到继承对象的C++类型转换
- 为什么 QObject ::findChildren 返回具有公共基类的子项