2
我正在使用QObject作爲組合模式的基類。爲什麼QObject :: findChildren返回具有公共基類的子代?
說我有一個父類文件(在一個人爲的例子)到我添加不同的類型,HeaderSection和PageSection的孩子。文件,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();
我得到以下輸出:
標題
字幕
PAGEONE
PageTwo
缺少什麼我在這裏?當然,如果findChildren尋找共同的基類,那麼它只會返回一個Widget的每個孩子(例如),我知道它不是正常使用。
另外,如果我遍歷返回兒童的名單和每個返回的孩子使用dynamic_cast<Page*>
,我得到預期的兩級的項目。
在每一類 –
道歉的頂部添加Q_OBJECT宏 - 這是完整的代碼,我在這裏省略了。我會糾正的。它只在基類中需要,順便說一句。 – mike
@mike:沒有,它需要從Qobject派生的所有類 - http://stackoverflow.com/questions/3689714/when-should-q-object-be-used;只有偏離,如果你是100%肯定的你在做什麼(包括100%確定你不是依靠像'qobject_cast'我相信的東西 - 但在很長一段時間沒有做Qt的東西)都 – Mat