[ fromfile: children.xml id: findchildren ]
Each QObject can have an unlimited number of QObject children. The addresses of these children are stored in a special container of QObject pointers. [64] QObject has a member function that returns a list of pointers to all the child objects of the host object. The prototype for this function is
const QObjectList& QObject::children() const
The order in which the child objects appear in the list is (initially) the order in which they were added to the list. There are certain runtime operations that can change that order.[65]
QObject also provides two overloaded (recursive) functions named findChildren()
.
Each returns a list of children that satisfy certain conditions.
The prototype of one of the overloaded forms looks like this:
QList<T> parentObj.findChildren<T> ( const QString& name = QString() ) const
The function returns a list of child objects of type T that have an object name equal to name.
If name is the empty string, findChildren()
works as a class filter – returning a QList of pointers to all children that can can be cast to type T
.[66]
Example 8.1 shows how to call this function. You must supply a template parameter after the function name.
Example 8.1. src/findchildren/findchildren.cpp
[ . . . . ] /* Filter on Customer* */ QList<Customer*> custlist = parent.findChildren<Customer*>(); foreach (const Customer* current, custlist) { qDebug() << current->toString(); } [ . . . . ]
<include src="src/findchildren/findchildren.cpp" href="src/findchildren/findchildren.cpp" id="findchildrencpp" allfiles="1" mode="cpp"/>
This is a simple example so, to make it more realistic, imagine the parent
object is a SalesManager
whose child list may contain pointers to Supplier
, SupportStaff
, and SalesPerson
objects which, in turn, have child lists that may contain pointers to Customer
, TravelAgent
, and other associated objects.
[64] Recall: any object derived from QObject is called a QObject. Also, a QObject pointer can store the address of a derived object.
[65] e.g., raising (or lowering) a QWidget child, which visually places the widget in front of (or behind) all overlapping sibling widgets
[66] Section 19.7 discusses type conversion and casting.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |