問題出現在標題中。在the documentation中我找不到任何明顯的表示這樣做的方法。我是否必須使用遞歸子查找方法並依次測試每個孩子的父指針以篩選出非直接的孩子?是否有一個簡單的方法來限制QObject :: findChild()僅指導孩子?
順便說一下,文檔似乎指的是「直接的祖先」,我認爲它的意思是「直系後裔」。
(編輯:我在尋找簡單,所以答案不必使用findChild()
法)
問題出現在標題中。在the documentation中我找不到任何明顯的表示這樣做的方法。我是否必須使用遞歸子查找方法並依次測試每個孩子的父指針以篩選出非直接的孩子?是否有一個簡單的方法來限制QObject :: findChild()僅指導孩子?
順便說一下,文檔似乎指的是「直接的祖先」,我認爲它的意思是「直系後裔」。
(編輯:我在尋找簡單,所以答案不必使用findChild()
法)
我有added一個標誌來QObject::findChild() Qt中5名爲Qt::FindDirectChildOnly
,它允許你做的正是這一點。
那麼這個問題將很快成爲過去的問題:-)
QObject* find(QObject* parent, const QString& objName)
{
foreach (QObject* child, parent->children())
{
if (child->objectName() == objName)
{
return child;
}
}
return 0;
}
肯定的答案(所以謝謝你),但我不希望靠'objectName'設定。如果父母和孩子沒有設置他們的名字,這很容易產生誤報。 – 2012-01-05 11:08:23
template <class T>
T findDirectChild(const QObject* parent, const QString& name = QString())
{
foreach (QObject* child, parent->children())
{
T temp = qobject_cast<T>(child);
if (temp && (name.isNull() || name == child->objectName()))
return temp;
}
return 0;
}
,將過濾器的基礎上可選名稱類型的模板版本。 根據TheHorse的回答。
根據the answer given by skyhisi的確切答案將按如下方式執行,這更符合我的需求。
ChildClass const * ParentClass::_getPointerToDirectChild() const
{
QObjectList allDirectChildren = this->children();
QObject * anObject = 0;
ChildClass const * aChild = 0;
while (allDirectChildren.isEmpty() == false)
{
anObject = allDirectChildren.takeFirst();
aChild = qobject_cast<ChildClass *>(anObject);
if (aChild) return aChild;
}
return aChild;
}
使用循環中的takeFirst()清空容器是非常緩慢的解決方案。在可能的情況下優先使用常量迭代,在這裏肯定是這種情況。 – 2012-02-23 17:48:53
同意性能我不會使用這個,但我會認爲這是過早的優化,我明確指出「我正在尋找簡單性:) :) – 2012-02-23 18:24:52
常量迭代不是比這更復雜(它實際上更簡單),而且我認爲,如果對「好」和「壞」的方式有一個明確的指導方針,那麼正確地做一些事情並不是過早的優化。除非這是一個一次性的項目,否則這正是會回來咬你的那種東西。 – 2015-10-09 17:58:42
你是明星:)你有鏈接到變更請求? – 2012-02-23 18:21:23
https://qt.gitorious.org/qt/qtbase/merge_requests/40 – 2012-02-23 18:44:42